(jQuery 1.4.4) I have a checkbox that has a .change() listener that works fine for when the user clicks the checkbox, but now I also need it to fire when I programmatically change the checkbox in jQuery, using .attr('checked', 'checked'). I'm perfectly happy to use other methods to make this work. Thanks.
$('#foo').attr('checked', 'checked'); // programmatically change the checkbox to checked, this checks the box alright
$('#foo').change( function() {
// this works when user checks the box but not when the above code runs
}
If you're using jQuery > 1.6, you can do this quite smartly by defining a attrHook
;
jQuery.attrHooks.checked = {
set: function (el, value) {
if (el.checked !== value) {
el.checked = value;
$(el).trigger('change');
}
}
};
As pointed out in the comments, the if
avoids a change
event triggering if the new value is the same as the old value.
... Although really you should be using prop()
anyway, so it should be;
jQuery.propHooks.checked = {
set: function (el, value) {
if (el.checked !== value) {
el.checked = value;
$(el).trigger('change');
}
}
};
You can see this working here; http://jsfiddle.net/2nKPY/
For jQuery < 1.6 (or if you don't fancy adding a propHook
) the best you can do is override the attr()
method (or upgrade :));
(function () {
var existingAttr = jQuery.fn.attr;
jQuery.fn.attr = function (attr) {
var result = existingAttr.apply(this, arguments);
if (result instanceof jQuery && attr == "checked") { // If we're dealing with a check-set operation.
result.trigger('change');
}
return this;
};
}());
You can see this in operation here
How about:
$('some selector').trigger('click');
Use jquery click()
to change the state of the checkbox rather than changing its attribute.
Not having all your markup I'm not sure how suitable this would be, but I've used this method recently to good effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With