Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 63816  / 12 Years ago, sun, april 22, 2012, 12:00:00

I'm trying to check a checkbox using jQuery and trigger the onclick event in the process.



Say I have a checkbox defined in html:



<input type=checkbox value=checked name=check1 onclick=alert(this.value);>


And I have a jQuery statement that is triggered in a function:



$('input[name=check1]').attr('checked', true);


The result is the checkbox gets checked but the javascript onclick event is not triggered (hence no alert). But if I were to trigger the click even manually as such:



$('input[name=check1]').attr('checked', true).trigger('click');


The result is the checkbox gets checked, javascript onclick event is triggered (and the value is correctly gotten) but then the checkbox gets unchecked after that.



Can anyone tell me how I can achieve what I'm trying to do?


More From » jquery

 Answers
22

Use .triggerHandler() instead of .trigger():



$('input[name=check1]').attr('checked', true).triggerHandler('click');


Also, use .prop() instead of .attr():



$('input[name=check1]').prop('checked', true).triggerHandler('click');


(if you're using jQuery 1.6 or newer.) edit — Also, as I commented on another answer, you have to watch out for jQuery's weird behavior when programmatically triggering events. Here is an illustrative jsfiddle. When a real click happens on an element, the click handler for the element will see the updated value of the checked flag. That is, if you click on an unchecked checkbox, the click handler will see the checked flag set to true. However, if you trigger click on an unchecked checkbox via jQuery, the click handler will see the checked flag set to false! That's a really bad thing, in my opinion, but it's always done that.



edit again — oh, also, I forgot another important (and irritating) jQuery weirdness: for reasons unknown, the .triggerHandler() API will only invoke handlers on the first matched element. If you try to trigger all the checkbox click handlers, in other words:



$('input:checkbox').triggerHandler('click');


then only the first checkbox on the page will be triggered. What I generally do in order to deal with the insanity is bind the handler with my own fake event name as well as click:



$('input:checkbox').bind('click my-click', function() ... ) // or .on() with 1.7


That way I can trigger my-click and get the best of both worlds: the library triggers the handler on all the matched elements, but it won't toggle the actual state of the elements.


[#86072] Saturday, April 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;