开发者

How to toggle the state of a master Checkbox using jQuery

开发者 https://www.devze.com 2023-02-19 02:41 出处:网络
I have a list of CheckBoxes that are ALL toggled on/off by a \"master\" CheckBox. I am using jQuery to do this and it works well.

I have a list of CheckBoxes that are ALL toggled on/off by a "master" CheckBox. I am using jQuery to do this and it works well.

What I would like to accomplish is to toggle OFF the "master" CheckBox whenever any of the CheckBoxes in the list are unchecked. Likewise if ALL of the CheckBoxes are "checked" I would like to have the "master" CheckBox checked also. This way the master CheckBox is not only a means to toggle all of the CheckBoxes on/off together, but it is also an indicator if all of them are checked.

Here is my current code which toggles the checkboxes ...

<input id="MasterCheckbox" type="checkbox" onclick="toggleChecked(this.checked)" />

<input id="checkbox1" type="checkbox" class="checkboxlistitem" />
<input id="checkbox2" type="checkbox" class="checkboxlistitem" />
<input id="checkbox3" type="checkb开发者_如何学Cox" class="checkboxlistitem" />

The jQuery function

function toggleChecked(status) {
  $(".checkboxlistitem").each(function () {
    $(this).attr("checked", status);
  })
}

Any suggestions on how to get the master CheckBox to toggle based on the status of the list of Checkboxes it controls? Yipe! That is a Checkbox tongue twister.


$("#MasterCheckbox").change(function() {
    $(".checkboxlistitem").attr("checked", this.checked);
});

$(".checkboxlistitem").change(function() {
    $("#MasterCheckbox").attr("checked", $(".checkboxlistitem:checked").length == $(".checkboxlistitem").length);
});

You can try it here.


Try this:

$("#MasterCheckbox").attr("checked", $(".checkboxlistitem:not(:checked)").length==0)

Sample Code:

<input id="MasterCheckbox" type="checkbox" onclick="toggleChecked(this.checked)" />  
<input id="checkbox1" type="checkbox" class="checkboxlistitem" /> 
<input id="checkbox2" type="checkbox" class="checkboxlistitem" /> 
<input id="checkbox3" type="checkbox" class="checkboxlistitem" /> 

    <script type="text/javascript">  

        function verifyMasterCheckbox() {
                $("#MasterCheckbox").attr("checked", $(".checkboxlistitem:not(:checked)").length == 0);
        }

        $(function() {
                $(".checkboxlistitem").click(function() {
                        verifyMasterCheckbox();
                });
        });
    </script>    
0

精彩评论

暂无评论...
验证码 换一张
取 消