Search code examples
jquerytogglepreventdefault

should I use preventDefualt() or stopPropagation() in this jquery and how?


var flip1 = 0;
$( ".car-row" ).click(function() {
    $( ".car-types" ).toggle( );
});

When div class ".car-row" is clicked, its subdiv '.cartypes' is toggled.

$('input[name=allcheck-cars]').click(function() {
    $("input[name='checkbox']").prop('checked', this.checked);
});

On clicking the checkbox, I just want the checkboxes in the subdiv to be checked/unchecked which I am able to do it. At the same time, when I click this checkbox which is in the same div class ".car-row", the subdiv ".cartypes" again gets toggled which I dont want to happen. So I need to use .preventDefault() anywhere to prevent toggling subdiv on click of checkbox. Please help.

http://jsfiddle.net/zMPJQ/


Solution

  • All you need to do is add capture the first parameter in the anonymous function, which contains the event. On this event you can call the preventDefault.

    $('input[name=allcheck-cars]').click(function(e){
        event.stopPropagation();
        $("input[name='checkbox']").prop('checked', this.checked);
    });