javascriptjquerycheckboxselectall

How to check the Select all checkbox after checking all its child checkboxes?


I want to check all the checkboxes upon checking the "Selectall" checkbox and vice versa if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. If I uncheck any of it's child checkboxes then the "Select all" checkbox should also be unchecked.

In my code, all the things are working except one thing that if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. Can anyone help me in making this thing workable for me. For your reference I'm giving my file code (HTML and Javascript code) here, so that you could test on your local machine.:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
    $("#ckbCheckAll").click(function () {
        $(".checkBoxClass").prop('checked', $(this).prop('checked'));
    });

    $(".checkBoxClass").change(function(){
        if (!$(this).prop("checked")){
            $("#ckbCheckAll").prop("checked",false);
        }
    });
});
</script>
</head>
<body>
<input type="checkbox" id="ckbCheckAll" /> Check All
    <p id="checkBoxes">
        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />
        <br />
    </p>
</body>
</html>

Solution

  • You can check how many checkboxes are there and how many are checked:

    $(".checkBoxClass").change(function(){
        var all = $('.checkBoxClass');
        if (all.length === all.filter(':checked').length) {
            $("#ckbCheckAll").prop("checked", true);
        } else {
            $("#ckbCheckAll").prop("checked", false);
        }
    });
    

    Not sure if all can be just $(this);