通过选中一个复选框来切换一组复选框[复制]

时间:2022-11-07 13:44:27

This question already has an answer here:

这个问题在这里已有答案:

I am trying to check a checkbox, and have that action check the remaining checkboxes in my form. How can I do this using classes?

我正在尝试选中一个复选框,并让该操作检查表单中的其余复选框。我怎样才能使用类?

<script>
    $(".global").on("click", function() {
        var all = $(this);
        $('.checkbtn').each(function() { 
            $(this).prop("checked", all.prop("checked"));
        });
    });
</script>

<div>
    <input type="checkbox" class ="global" id="select-all" name="selectAll" value=""/> All
    <input type="checkbox" class ="checkbtn" name="practice" value=""/> 1
    <input type="checkbox" class ="checkbtn" name="filename" value=""/> 2
    <input type="checkbox" class ="checkbtn" name="comment" value=""/> 3
</div>

1 个解决方案

#1


1  

You are unnecessarily complicating this task. Go this way:

您不必要地使此任务复杂化。走这条路:

$(function() {
  $(".global").on("change", function() {
    var state = this.checked;
    $('.checkbtn').prop("checked", state);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="global" id="select-all" name="selectAll" value="" />All
<input type="checkbox" class="checkbtn" name="practice" value="" />1
<input type="checkbox" class="checkbtn" name="filename" value="" />2
<input type="checkbox" class="checkbtn" name="comment" value="" />3

#1


1  

You are unnecessarily complicating this task. Go this way:

您不必要地使此任务复杂化。走这条路:

$(function() {
  $(".global").on("change", function() {
    var state = this.checked;
    $('.checkbtn').prop("checked", state);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="global" id="select-all" name="selectAll" value="" />All
<input type="checkbox" class="checkbtn" name="practice" value="" />1
<input type="checkbox" class="checkbtn" name="filename" value="" />2
<input type="checkbox" class="checkbtn" name="comment" value="" />3