Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Checkbox with jQuery on parent click

I have the following code example: http://jsfiddle.net/sX3w9/

$('.item').on('click', function() {
            var checkbox = $(this).find('input');
            checkbox.attr("checked", !checkbox.attr("checked"));    
            $(this).toggleClass('selected');
        });

Where a user should be able to click the div.item and/or the checkbox inside it and it should check or uncheck the checkbox and add or remove the selected class from the div.

It works when clicking the div, but clicking the checkbox instantly unchecks it again...

like image 505
Cameron Avatar asked Dec 27 '22 01:12

Cameron


1 Answers

Try the following code:

$('.item').on('click', function() {
            var checkbox = $(this).find('input');
            checkbox.attr("checked", !checkbox.attr("checked"));    
            $(this).toggleClass('selected');
        });
$(".item input").on("click", function(e){
    e.stopPropagation();
    $(this).parents(".item").toggleClass('selected');
});

The problem is that when you check checkbox clicking on div occurs and it makes checbox unchecked again.

like image 165
cycaHuH Avatar answered Jan 07 '23 07:01

cycaHuH