[jquery] jQuery checkbox check/uncheck

What would be a proper way to check/uncheck checkbox that's placed inside the element that triggers my function?

Here's my code:

<table id="news_list">
<tr>
    <td><input type="checkbox" name="news[1]" /></td>
    <td>TEXT</td>
</tr></table>

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.removeAttr('checked');
        $(this).removeClass('admin_checked');
    }else{
        ele.attr('checked', 'checked');
        $(this).addClass('admin_checked');
    }
});

The problem is I can check and uncheck each box only once. After I've checked and unchecked sometimes it still does add/remove class, but never checking a box again (even when I click on checkbox, not table row).

I've tried using .bind('click') trigger, but it's the same result.

Any solutions?

This question is related to jquery checkbox

The answer is


Use prop() instead of attr() to set the value of checked. Also use :checkbox in find method instead of input and be specific.

Live Demo

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.prop('checked', false);
        $(this).removeClass('admin_checked');
    }else{
        ele.prop('checked', true);
        $(this).addClass('admin_checked');
    }
});

Use prop instead of attr for properties like checked

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method


 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});