jquery check all checkboxes and add class to rows?
I am trying to add a class to my tr rows if the select all checkbox has been selected, but I can't seem to get the add class to work (and then obviously remove them if check all has been deselected), I am using toggle on each individual row to add/remove the class, but can't seem to get it working for the check all.
Here's my table:
<form>
<table cellspacing="0" cellpadding="0" class="tablesorter" id="table">
<thead>
<tr>
<th valign="middle" align="left" class="filebox"><input type="checkbox" id="checkall" name="checkall"></th>
<th valign="middle" align="left" class="header filename"><strong>Filename</strong></th>
<th valign="middle" align="left" class="header filesize"><strong>Size</strong></th>
<th valign="middle" align="left" class="header filedate"><strong>Date</strong></th>
</tr>
</thead>
<tbody class="file">
<tr>
<td valign="middle" align="left" class="filebox"><input type="checkbox" id="checkbox" name="checkbox"></td>
<td valign="middle" align="left" class="filename">Search48.png&l开发者_StackOverflow社区t;/td>
<td valign="middle" align="left" class="filesize">6 KB</td>
<td valign="middle" align="left" class="filedate">21/10/2010</td>
</tr>
<tr>
<td valign="middle" align="left" class="filebox"><input type="checkbox" id="checkbox" name="checkbox"></td>
<td valign="middle" align="left" class="filename">shopping_trolley48.png</td>
<td valign="middle" align="left" class="filesize">3 KB</td>
<td valign="middle" align="left" class="filedate">21/10/2010</td>
</tr>
</tbody>
</table>
</form>
Here's my jquery code:
//check all checkboxes
$("#checkall").click(function () {
$(this).parents("#table:eq(0)").find(":checkbox").attr("checked", this.checked);
});
//add highlight to tr
$("#checkbox").click(function() {
$(this).parent().parent().toggleClass("highlight");
});
You cant use an ID here since it's repeated, instead use a class like class="checkbox"
instead of the id="checkbox"
, like this:
$("#checkall").change(function () {
$(this).closest("table").find(":checkbox").attr("checked", this.checked).change();
});
$(".checkbox").change(function() {
$(this).closest('tr').toggleClass("highlight", this.checked);
});
You can test it out here. Also note the use of change
instead of click
so the state is correct, the use of closest()
to get the nearest parent of that selector, and calling .change()
on all the checkboxes you're changing, so their row class gets updated correctly.
http://beckelman.net/2008/11/18/select-all-checkboxes-in-a-table-column-with-and-without-jquery-plugin-demo/
<script type="text/javascript">
$(document).ready(function() {
$("#tableOne thead tr th:first input:checkbox").click(function() {
var checkedStatus = this.checked;
$("#tableOne tbody tr td:first-child input:checkbox").each(function() {
this.checked = checkedStatus;
});
});
});
</script>
精彩评论