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?
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.
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).
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.
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:
input
to :checkbox
.the length
of the checked checkboxes
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With