我正在使用 JQuery 模板,并且尝试添加全选复选框。在原始 ajax 调用中,我将分类的每个 ID 添加到数组中。然后使用该数组来选择每个复选框。
这些复选框的默认行为是在选中时在每个复选框下方显示一个输入框。我希望全选复选框也可以切换这些输入。所以问题是,在检查 selectAll 后,它打开和关闭每个切换大约 5 次。
我相信这与我的 .each 方法中的嵌套 forloop 有关,但并不完全确定。
代码如下:
vendorClassifications = [];
$('#selectall')
.click(function() {
if (this.checked) {
$('#step1data input:checkbox')
.each(function() {
this.checked = true;
for (var i = 0; i <= vendorClassifications.length; i++) {
if (vendorClassifications.hasOwnProperty(i)) {
$('#search_options_' + vendorClassifications[i]).toggle('blind');
}
}
});
} else {
$('#step1data input:checkbox')
.each(function() {
this.checked = false;
for (var i = 0; i <= vendorClassifications.length; i++) {
if (vendorClassifications.hasOwnProperty(i)) {
$('#search_options_' + i).toggle('blind');
}
}
});
}
});
最佳答案
一次获取所有复选框比您想象的要简单得多
// Gather up all the checkboxes
var boxes = document.querySelectorAll("input[type=checkbox]");
而且,将它们全部选中也很简单:
boxes.forEach(function(box){
box.setAttribute("checked","checked");
});
并且,同时打开关联元素的显示意味着仅添加一行:
boxes.forEach(function(box){
box.setAttribute("checked","checked");
box.nextElementSibling.style.display = "inline";
});
最后,将所有这些都绑定(bind)到“全选”按钮:
window.addEventListener("DOMContentLoaded", function(){
// Get the Select All button
var btn = document.getElementById("btnSelect");
// Gather up all the checkboxes
var boxes = document.querySelectorAll("input[type=checkbox]");
// Set up click handler for checkboxes
boxes.forEach(function(box){
box.addEventListener("change", function(){
// Tie the checked property value to the display of the input next to it
this.nextElementSibling.style.display = this.checked ? "inline" : "none" ;
});
});
// Set up a click event handler for the button
btn.addEventListener("click", function(){
// that loops the checkboxes and sets them all to checked
// and displays their neighbor
boxes.forEach(function(box){
box.checked = true;
box.nextElementSibling.style.display = "inline";
});
});
});
input[type="text"] {display:none;}
<input type="checkbox" value="box1"><input type="text">
<input type="checkbox" value="box2"><input type="text">
<input type="checkbox" value="box3"><input type="text">
<input type="checkbox" value="box4"><input type="text">
<button id="btnSelect">Select All</button>
关于javascript - 选择所有复选框并切换输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41151269/