Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery checkbox check/uncheck [duplicate]

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?

like image 597
user1587985 Avatar asked Feb 08 '13 09:02

user1587985


People also ask

How can I uncheck checkbox is checked in jQuery?

By using jQuery function prop() you can dynamically add this attribute or if present we can change its value i.e. checked=true to make the checkbox checked and checked=false to mark the checkbox unchecked.

How do I uncheck another checkbox on one?

You can uncheck the other checkboxes in the row by clicking on any one checkbox in the same row by customization the CellCheckBoxClick event in WinForms DataGrid (SfDataGrid).

How check if checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.


1 Answers

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

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

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.
like image 87
Jai Avatar answered Sep 30 '22 07:09

Jai