Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click a div to check / uncheck a checkbox

Tags:

jquery

I applied the following code to make table rows check/uncheck a child checkbox when clicked. Now I discovered that when clicking the checkbox itself inside the row it doesent check. Could it be that it checks on click (standard function) and then the jquery picks up the click event and unchecks it? How can I fix this?

//check on div click
$("tr").live("click",function() {
    var checkbox = $(this).find("input[type='checkbox']");

    if( checkbox.attr("checked") == "" ){
        checkbox.attr("checked","true");
    } else {
        checkbox.attr("checked","");
    }
});
like image 338
Joseph Avatar asked May 21 '11 18:05

Joseph


Video Answer


2 Answers

I suspect that the click event is bubbling from the checkbox to the tr. Try adding this code as well:

$('tr input[type=checkbox]').click(function(e){
        e.stopPropagation();
});

EDIT

here's an example: http://jsfiddle.net/GSqNv/

like image 200
Stuart Burrows Avatar answered Sep 19 '22 16:09

Stuart Burrows


Check the target of the caller is not a checkbox

$("tr").live("click",function(event) {
    var target = $(event.target);
    if (target.is('input:checkbox')) return;

    var checkbox = $(this).find("input[type='checkbox']");

    if( checkbox.attr("checked") == "" ){
       checkbox.attr("checked","true");
    } else {
       checkbox.attr("checked","");
    }
});

DEMO http://jsfiddle.net/7Bze7/

The code above checks that the sender of the event is not a checkbox.

like image 43
aleemb Avatar answered Sep 21 '22 16:09

aleemb