我正在使用JQuery模板,而我正在尝试添加一个全选复选框。在原始的ajax调用中,我将分类的每个ID添加到数组中。然后使用该数组选择每个复选框。
这些复选框的默认行为是选中时每个输入框都显示在下面。我希望它能使select all复选框也切换这些输入。所以问题是在检查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');
}
}
});
}
});
答案 0 :(得分:1)
立即获取所有复选框比您想象的要简单得多
// 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";
});
最后,将所有这些与#34; Select All&#34;按钮:
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";
});
});
});
&#13;
input[type="text"] {display:none;}
&#13;
<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>
&#13;