Search code examples
javascriptjqueryeventsstoppropagationevent-propagation

stopPropagation() of a different event


How can I listen to a change event on a checkbox without triggering a click event on its container?

<label><input type="checkbox"> Hello world</label>

I want to trigger an action on the checkbox's change event, but I don't want it to bubble up to a click event on the label.

(function ($) {
    $('input').change(function (v) {
        v.stopPropagation();
    });

    $('label').click(function () {
        alert('You should not see this message if you click the checkbox itself!');
    });
})(jQuery);

http://jsfiddle.net/r49PA/

Any ideas? Thanks!


Solution

  • The issue is that two events are triggered when you click the checkbox -- a change and a click. You're only catching the change, so the click isn't ever being told to stop propagation. You need to either add a second handler on the checkbox for click events, or combine one handler to catch both types, like this:

    $('input').on('change, click', function (v) {
        v.stopPropagation();
    });
    

    Here's a jsFiddle demonstrating a combined handler: http://jsfiddle.net/r49PA/4/