Pages

Monday, August 26, 2013

Select All Checkbox using jQuery

Select All checkbox are used to select multiple records at a time.
If user select/deselect the select all checkbox, all the checkbox in table will get selected or deselected accordingly.
Suppose if user select all the checkbox one by one then the select all checkbox should be automatically gets selected, and if user click selectall first and then unchecks any of the checkbox, then the select all also should be unchecked automatically.

Code for HTML Table

<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Programming Language</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>PHP</td>
<td>5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>JSP</td>
<td>4</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
<td>ASP</td>
<td>3</td>
</tr>
</table>

The JQuery Code

Add following jQuery code in HEAD section of above HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<SCRIPT language="javascript">
$(function(){

// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});

// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){

if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}

});
});
</SCRIPT>

















Here in above code at Line 08, we register a handler on click of selectall checkbox. On click of this checkbox, we check/uncheck all checkbox in the datatable.
Also check the Line 14, where we check the selectall checkbox, if all the checkbox are selected manually.

No comments:

Post a Comment