05 July, 2010

Check All - Uncheck All multiple checkboxes using jquery

Sometimes later, i had to check and/or uncheck multiple checkboxes having same name being displayed dynamically). I have one checkbox for Check/Uncheck All, and depending on that, i had to check or uncheck other checkboxes. And if any one of the checkboxes, besides main checkbox, was checked or unchecked, then i would have to check or uncheck the main checkbox as well.
The text i have writte here might seem little confusing than the original source code, but the main point is i had to check/uncheck multiple checkboxes at once. So here is the jquery code that i wrote for doing the same.

$(document).ready(function() {
//get count of checkboxes with the same name
var countBoxes = $("input[name='chkTest[]']").size();
//move through each checkbox
$("input[name='chkTest[]']").each(function() {
$(this).click(function() {
//get the state, checked or not, i.e. true or false
var state = $(this).attr("checked");
//get the length of checked checkboxes
var chkedLength = $("input[name='chkTest[]']:checked").length;
//make the checked or unchecked state
var chkAllState = (chkedLength == countBoxes) ? true : false;
//now apply the state to main checkbox
$("input[name='chkAll']").attr("checked", chkAllState);
});
});
//this code checks or unchecks all sub-checkboxes depending on checked state
$("input[name='chkAll']").click(function() {
var chkAllStatus = $(this).attr('checked');
$("input[name='chkTest[]']").attr("checked", chkAllStatus);
});
});

No comments: