I have a table with a column full of checkboxes. At the top I would like to have a single "Select All" checkbox that would check all the checkboxes on that page.
How should I implement this? I'm using jQuery as my JavaScript framework if it matters.
I have a table with a column full of checkboxes. At the top I would like to have a single "Select All" checkbox that would check all the checkboxes on that page.
How should I implement this? I'm using jQuery as my JavaScript framework if it matters.
jquery (EDITED to toggle check/uncheck all):
$(document).ready(function() {
$("#toggleAll").click(function() {
if ($(this).attr("checked")) {
$("#chex :checkbox").attr("checked", true);
} else {
$("#chex :checkbox").attr("checked", false);
}
});
});
The reason why I had to do a click() then an if statement to check for checked status is because if you try to "toggle" a checkbox, the checkbox being toggled will not retain its checked status. This way it retains the check status and effectively toggles.
HTML:
<input type="checkbox" id="toggleAll" />
<div id="chex">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
KingNestor:
You are also going to need this link (if you haven't already discovered it):
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysLists...
While the answers posted previously will work, you'll run into issues if you have more than one set of checkboxes in a single page.
This format will work regardless:
<table>
<thead>
<tr>
<th><input type="checkbox" /></th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" /></td>
<td>Tabular Data 1</td>
<td>Tabular Data 2</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Tabular Data 3</td>
<td>Tabular Data 4</td>
</tr>
</tbody>
</table>
and the script...
$(function() {
$('th > :checkbox').click(function() {
$(this).closest('table')
.find('td > :checkbox')
.attr('checked', $(this).is(':checked'));
});
});
This will keep all the individual checkboxes the same as the "check all" one
$("#id-of-checkall-checkbox").click(function() {
$(".class-on-my-checkboxes").attr('checked', this.checked);
});
This will keep the "check all" one in sync with whether or not the individual checkboxes are actually all checked or not
$(".class-on-my-checkboxes").click(function() {
if (!this.checked) {
$("#id-of-checkall-checkbox").attr('checked', false);
}
else if ($(".class-on-my-checkboxes").length == $(".class-on-my-checkboxes:checked").length) {
$("#id-of-checkall-checkbox").attr('checked', true);
}
});