Reputation: 1282
Is there a way to add an event handler (like .on('change' ..)
to a checkbox when it becomes disabled?
I tried this (see jsfiddle), but it does not fire when I disable the checkbox:
$('#myCB').on('change', function() {
console.log('checkbox disabled? ' + $('#myCB').is(':disabled'));
});
$('#myCB').prop('disabled', true); // does NOT trigger the function above
Edit: I want to add the logic to the checkbox only because in my application I don't know when the checkbox might become disabled.
Upvotes: 1
Views: 967
Reputation: 1282
Actually I just found this nice way to trigger the change event every time the properties change:
var oldProp = $.fn.prop;
var newProp = function() {
// console.log('$(..).prop() called');
// execute jQuery's .prop() method
var retFunc = oldProp.apply(this, arguments);
// afterwards trigger custom event
this.trigger('property_changed', this);
return retFunc;
}
// replace jQuery's .prop() function with the new one
$.fn.prop = newProp;
Now every time I call .prop()
on any element it will automatically trigger my custom change event. See the updated jsfiddle.
Edit: As rahul maindargi mentioned in his comment it is better to use a custom event instead of the "change" event itself. I have updated my code so that it uses custom events now.
Upvotes: 1
Reputation: 5635
My best guess is that you want to listen to DOM mutation events. You can do that by DOM mutation event as any normal javascript event such as a mouse click.
Refer to this : http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-MutationEvent
Example:
$("element-root").bind(DOMSubtreeModified,"CustomHandler");
Upvotes: 1
Reputation: 2114
The change event gets fired when the value of the field changes (so when the checkbox gets checked). It does not work on the disabling.
Firing an event on disabling the checkbox might be tricky to do. See here.
Upvotes: 1
Reputation: 74420
The simplest way should be:
$('#myCB').prop('disabled', true).triggerHandler('change');
Upvotes: 2