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 are using jQuery 1.6 or later.) edit - Also, since I commented on a different answer, you have to keep an eye on the strange behavior of jQuery when programmatically triggering events. Here is an illustrative jsfiddle. When the real “click” occurs in the element, the “click” handler for the element will see the updated value of the “checked” flag. That is, if you click the check box without a checkmark, the click handler will see the “checked” flag set to true . However, if you run "click" on a flag without checking through jQuery, the "click" handler will see the "checked" flag set to false ! This is really bad in my opinion, but it has always been done like that.
change again - Oh, besides, I forgot one more important (and annoying) jQuery oddity: for unknown reasons, the .triggerHandler() API will only call handlers for the first matching element. If you try to call all the click flags, in other words:
$('input:checkbox').triggerHandler('click');
then only the first flag on the page will be launched. What I usually do to deal with insanity is associating a handler with my own fake event name, as well as "click":
$('input:checkbox').bind('click my-click', function() ... ) // or ".on()" with 1.7
Thus, I can call "my click" and get the best of both worlds: the library starts the handler of all the agreed elements, but does not switch the actual state of the elements.
Pointy Apr 22 '12 at 13:15 2012-04-22 13:15
source share