Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10015

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?

Upvotes: 1

Views: 2802

Answers (2)

Alexander Kludt
Alexander Kludt

Reputation: 863

You need to use Even.stopImmediatePropagation()

$("#address_cb").change(function(event) {
   alert('foo');
   event.preventDefault();
   event.stopImmediatePropagation(); //Works
   return false; //would call event.preventDefault() and event.stopPropagation() but not stopImmediatePropagation()
});

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.

See event.preventDefault() vs. return false for differences on return false method

Upvotes: 5

Samir
Samir

Reputation: 1368

Try using event.stopImmediatePropagation() instead of event.stopPropagation();. Please test it propely. Hope this work. Reference https://api.jquery.com/event.stopimmediatepropagation/

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

Upvotes: 1

Related Questions