Check or Uncheck all checkboxes with master checkbox in jquery

In many sites you have seen this situation(example: in Gmail) where checking the master checkbox should check all the other child checkboxes or unchecking the master checkbox should uncheck all the other child checkboxes. So, in this post we are going to see how we can do this using JQuery.

Checking the all checkboxes when the header checkbox is checked


Lets create a group of checkboxes

<input type="checkbox" id="headerCheckbox"/>
 
    <input type="checkbox" class="childCheckBox" id="Checkbox1"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox2"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox3"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox4"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox5"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox6"/> 

We have created a header checkbox and some child checkboxes. We have used same class(class="childCheckBox") for all the child checkboxes which are related to the header checkbox. Now, if we check the header checkbox all the child checkboxes should be checked.

For that, use the below JQuery code

$('#headerCheckbox').click(function () {
    var isheaderChecked = this.checked;
    $(".childCheckBox").each(function () {
        this.checked = isChecked;
    })
})

The above code will check all checkboxes with the class "childCheckBox" and also if you uncheck the header checkbox then all the child checkboxes will be unchecked.

Unchecking the header checkbox when any one of the child checkbox is unchecked


When you uncheck any one of the child checkbox then the header checkbox should also be unchecked. For that case use the following JQuery code

$("input[type='checkbox']:not(:first)").click(function () {
    var allChecked = true;
    $("input[type='checkbox']:not(:first)").each(function () {
        if (this.checked == false) {
            allChecked = false;
            $('#headerCheckbox').prop('checked'false);
        }
    })
    if (allChecked == true) {
        $('#headerCheckbox').prop('checked'true);
    }
})

In this way you can check or uncheck all the checkboxes when a master checkbox is checked.

For more posts on Jquery please visit: JQuery

1 comment:

  1. Your tutorial is very nice and helpful, i also wrote tutorial how to select and deselect all checkboxes using jQuery, i hope you like it.
    https://htmlcssphptutorial.wordpress.com/2015/08/18/select-deselect-all-checkboxes-using-jquery/

    ReplyDelete