Select all checked boxes

I use select all checkboxes in the page by using this code:

$(function(){

    // add multiple select / deselect functionality
    $("#selectall").click(function () {
          $('.case').attr('checked', this.checked);
    });

    // if all checkbox are selected, check the selectall checkbox
    // and viceversa
    $(".case").click(function(){

        if($(".case").length == $(".case:checked").length) {
            $("#selectall").attr("checked", "checked");
        } else {
            $("#selectall").removeAttr("checked");
        }

    });
});

In this code select all checkedbox. But if we select some checkboxes and give select all it select all. After we again unchecked selected all but previous checked box remain checked.

Answers 1

  • The attr part of $('.case').attr('checked', this.checked); is incorrect: The current checked state of a checkbox is represented by the checked property. The checked attribute is just the default checked state for the input, not its current checked state. (Just like the difference between the value property and the value attribute.)

    To set the current state of the checkbox, use prop:

    $(function() {
    
        // add multiple select / deselect functionality
        $("#selectall").click(function() {
            $('.case').prop('checked', this.checked);
        });
    
        // if all checkbox are selected, check the selectall checkbox
        // and viceversa
        $(".case").click(function() {
            $("#selectall").prop("checked", $(".case").length == $(".case:checked").length);
        });
    });
    <div><label><input type="checkbox" class="case"> One</label></div>
    <div><label><input type="checkbox" class="case"> Two</label></div>
    <div><label><input type="checkbox" class="case"> Three</label></div>
    <div><label><input type="checkbox" class="case"> Four</label></div>
    <div><label><input id="selectall" type="checkbox"> ALL</label></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Related Articles