我根据数据库中的值选中/取消选中了 6 个复选框,第 5 个复选框未选中,为了获取状态,我使用下面的代码片段:
var allCheckboxes = $(':input[name="cc_checkbox"]').map(function () {
return this.value;
}).get();
当我 console.log(allCheckboxes)
时,我得到 ["1", "1", "1", "1", "0", "1"]
这是正确的。
但是当我选中/取消选中任何复选框和 console.log(allCheckboxes)
时,我仍然得到 ["1", "1", "1", "1",“0”,“1”]
这是正常行为还是我需要使用其他语法?
最佳答案
问题是因为复选框的值
始终存在。它不会根据元素是否被检查而改变。
要解决此问题,您可以将元素的 checked
属性放入数组中:
var allCheckboxes = $(':input[name="cc_checkbox"]').map(function () {
return this.checked;
}).get();
鉴于您的OP中的示例,这将为您提供以下数组输出:
[true, true, true, true, false, true]
关于javascript - 每次选中或取消选中时更新复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46649025/