Need checkbox change event to respond to change of checked state done programmatically
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.