Check and Uncheck all checkboxes using jquery
There are some simple things to do in programming yet some developers find it tough. This is an example of checking all the checkboxes in a page using jquery. For this to work , you need jquery.js file included in your page.
This is the body part with all the checkboxes:
<table>
<tr>
<td align=”left” colspan=”4″><input type=”checkbox” class=”checkAll”></td>
</tr>
<tr>
<td> <input type=”checkbox” name=”myChkBox” class=”selectedId” id=”myChkBox1″ /> </td>
<td> <input type=”checkbox” name=”myChkBox” class=”selectedId” id=”myChkBox2″ /> </td>
<td> <input type=”checkbox” name=”myChkBox” class=”selectedId” id=”myChkBox3″ /> </td>
<td> <input type=”checkbox” name=”myChkBox” class=”selectedId” id=”myChkBox4″ /> </td>
</tr>
</table>
This is the jquery code:
$(function () {
$(‘.checkAll’).click(function () {
$(‘.selectedId’).attr(‘checked’, this.checked);
});
$(‘.selectedId’).change(function () {
var check = ($(‘.selectedId’).filter(“:checked”).length == $(‘.selectedId’).length);
$(‘.checkAll’).attr(“checked”, check);
});
});
Please note here i have used class attribute in both the checkboxes(One for checkall and the other for ChkBox1……ChkBox4). The main check box for checking all the boxes has been given the class name as checkAll and all other sub checkboxes classname is given as selectedId. Thats it. All your check box will be checked and unchecked.