开发者

Checkbox does not change when clicked directly on it

I have a table of data and have one checkbox per row for the user to select the item.

I'm using the following jQuery code to allow the user to select the item by clicking anywhere in the row:

$("tbody tr").click(function() {
    var checkbox = $(this).find(':checkbox');
    checkbox.attr('checked', !checkbox.attr('checked'));
});

The problem is if I click directly on the checkbox, nothing happens. ie. if the checkbox is not checked, it remains unchecked. If I click anywhere else in the row, the checkbox changes status.

I'm thinking that the jQuery code is causing the action to be performed twice. If I click on the checkbox, the checkbox will change but then the jQuery code for clicking on the row will be performed and the checkbox will be changed back. Not sure if that is actually happening but that is my guess.

How can I get a check开发者_如何转开发box to be toggled when a user clicks on a row and the same thing if they click directly on the checkbox?


Check what item is being clicked by checking the event information. Then if it's a checkbox, don't run the code. Otherwise, toggle the checked attribute

$("tbody tr").click(function(e) {
        e = e || event;
        var isCheckbox = $(e.target).is(":checkbox");
        if (!isCheckbox) {
            var checkbox = $(this).find(':checkbox');
            checkbox.attr('checked', !checkbox.attr('checked'));
        }
});


Tt is because the checkbox is in the tbody tr. If you were to step through the code you would notice that it was checked but then unchecked by your click function. change your click function to exclude the td that holds the checkbox.

$("tbody tr td").click(function() { 
    if ($("input:checkbox", $(this)).length) {
       //td contains check box  do nothing
    } else {
      var checkbox = $(this).find(':checkbox'); 
      checkbox.attr('checked', !checkbox.attr('checked')); 
    }
}); 


You're catching a click event on the row. If the checkbox is within the TR then the event is getting triggered and you're inverting the "checked" attribute. One solution would be to place the event on each TD within the TR, except for the TD containing the checkbox.


If the problem is that the event is actually getting triggered twice (and that seems like a fair supposition), then you should try using the event.preventDefault() and event.stopPropagation() event methods. They should stop the event from reaching the checkbox itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜