1

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?

Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151

2 Answers2

5

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

Community
  • 1
  • 1
Alexander Kludt
  • 854
  • 6
  • 17
1

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;
}); 
Samir
  • 1,312
  • 1
  • 10
  • 16