简体   繁体   English

复选框切换所有选择

[英]Checkbox to toggle all selection

I have this javascript code 我有这个JavaScript代码

    // Listen for click on toggle checkbox
$('#select-all').click(function(event) {   
    if(this.checked) {
        // Iterate each checkbox
        $(':checkbox').each(function() {
            this.checked = true;                        
        });
    }
});

And I have this 我有这个

<form action="" method="POST">    
Toggle All : &nbsp;&nbsp;
<input type="checkbox" name="select-all" id="select-all" />

then at my table I have multiple checkbox 然后在我的桌子上我有多个复选框

<input type="checkbox" name="checkbox-1" id="checkbox-1" value="1"> Select
<input type="checkbox" name="checkbox-2" id="checkbox-2" value="2"> Select
<input type="checkbox" name="checkbox-3" id="checkbox-3" value="3"> Select
<input type="checkbox" name="checkbox-4" id="checkbox-4" value="4"> Select

When I click on toggle all, it does not check checkbox-1 to checkbox-4 当我单击全部切换时,它不会将复选框1选中到复选框4

What went wrong in my javascript code. 我的JavaScript代码出了什么问题。

Thanks!! 谢谢!! I want to actually do a function that will send all the value of checkbox1-4 by post when they are checked on form submit. 我实际上想做一个函数,当在表单提交中选中它们时,将通过邮寄发送checkbox1-4的所有值。

Simply do like this. 只需这样做。

$('#select-all').click(function(event) {
    $(':checkbox').prop("checked", this.checked);
});

You do not need to loop through each checkbox to check all. 您无需遍历每个复选框即可全部选中。

Demo 演示版

Wrap the code in dom ready if your script is in head tag 如果您的脚本位于head标签中,则将代码包装在dom中

$(document).ready(function() {
    $('#select-all').click(function(event) {
        $(':checkbox').prop("checked", this.checked);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM