Alex Zhukovskiy Alex Zhukovskiy - 6 months ago 40
jQuery Question

Prevent event firing for checkbox change

I have two event handlers for one single checkbox. I want to first handler to prevent the second one from firing. Here is an example:

$("#address_cb").change(function(event) {
alert('foo');
event.preventDefault();
event.stopPropagation();
return false;
});

$("#address_cb").change(function(event) {
alert('should never display');
});

$("#address_cb").trigger("change");


https://jsfiddle.net/zxzzLkky/5/


How can I achieve it?

Answer

You need to use Even.stopImmediatePropagation()

$("#address_cb").change(function(event) {
   alert('foo');
   event.preventDefault();
   event.stopImmediatePropagation(); //Works
   return false; //will do the same as above (plus stopPropagation)
});

as both of your events fire on the same event level. As an alternative you might just return false for your callback as jQuery will care about the rest.