how prevent the parent click event on change a checkbox

Viewed 2848

I have a checkbox inside a parent container which has a click event, whenever I try to click the checkbox parent click works first and following by the change event, I am using e.stopPropagation(); on both the parent and child events, but still, it's not working

// make the .parent react
 function grandParent(){
    alert('Grand Parent: You hit me, my child or my grand child, now deal with me!');
}

// make the .parent react
$('.parent').on('click', function(e){
    e.stopPropagation()
    alert('Parent : Don\'t you dare hitting me or my child, again!');
});

// make the child cry, when we hit him.
$('.child').on('click', function(e){
e.stopPropagation();
 alert('Child : waaaaaa waaaa waa huh huh waaa waaaa!');
});

$('.hello').on('change', function(e){
e.stopPropagation();
 alert('checkbox clicked');
});

Fiddle example

3 Answers

Sequence of the event matters , where the click event occurs first and Change event the next ,So in your case you need to change the type of event handling to Click click here to see the sequence / priority of events happening after clicking on check box

$('.hello').on('click change', function(e){
e.stopPropagation(); 
 alert('checkbox '+e.type);
});

This happens because e.stopPropagation(); is on change event and .child has click event. You can do this like in @rikpg example, but if you need change event, you should just add new one click event to checkbox that only has stopPropagation

http://jsfiddle.net/wppv2152/2/

Related