Checkbox does not change when clicked directly on it

Posted by Matt McCormick on Stack Overflow See other posts from Stack Overflow or by Matt McCormick
Published on 2010-05-21T14:59:51Z Indexed on 2010/05/21 15:00 UTC
Read the original article Hit count: 313

Filed under:
|

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 checkbox to be toggled when a user clicks on a row and the same thing if they click directly on the checkbox?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about checkbox