Selecting and Deselecting checkboxes using jQuery
In this article, I am going to explain you how to select and deselect a group of check-boxes using j Query. I am going to demonstrate this with a simple example which contains a master check-box followed by a group of child check-boxes. On selecting the master check-box, all the child check-boxes should be checked and on deselecting it, vice-versa takes place.
Selecting and deselecting of check-boxes is a simple functionality which is very often found in our daily web applications .Gmail is an easy example I can give you which we use daily.
There are three requirements to be fulfilled in our present functionality
Now let us consider our example.Let my HTML code look like this:
<form id="SelectAll" onsubmit="return function();" runat="server">
Select All :<input type="checkbox" id="masterCheckBox" />
<p id="checkBoxes">
Apple:<input type="checkbox" class="childCheckBox" id="chk1" />
Mango:<input type="checkbox" class="childCheckBox" id="chk2" />
Orange:<input type="checkbox" class="childCheckBox" id="chk3" />
Banana:<input type="checkbox" class="childCheckBox" id="chk4" />
</p>
</form>
Now our code in the JavaScript would be as followed:
$(document).ready(function () {
$("#masterCheckBox ").click(function () {
$(".childCheckBox ").prop("checked", this.checked);
$(".childCheckBox ").click(function () {
if ($(".childCheckBox").length == $(".childCheckBox:checked").length) {
$("#masterCheckBox").prop("checked", true);
}
else {
$("#masterCheckBox").prop("checked", false);
}
});
});
});
Copy and paste the code in your visual studio accordingly where needed and then run it. You will experience the result shown in the image below:
Hope this helps you understand how to select and deselect a list of check-boxes that might encounter in your application.
Thanks ketan..