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

  • When the master checkbox i.e. "select all" checkbox is selected all the checkboxes down to it i.e. all the child checkboxes should get selected automatically.

  • If any one of the child checkboxes is deselected the master checkbox should get deselected.

  • If all the child checkboxes are selected individually the parent checkbox should get selected automatically.

  • 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:
    Selecting and Deselecting checkboxes using jQuery
    Hope this helps you understand how to select and deselect a list of check-boxes that might encounter in your application.


    Comments

    Author: srikanthbattula18 Oct 2013 Member Level: Silver   Points : 0

    Thanks ketan..



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: