Reputation: 169
I'm using JQuery template and I'm trying to add a select all checkbox. In the original ajax call, I'm adding each ID of the classification to an array. Then using that array to select each checkbox.
The default behavior of these checkboxes are that an input box shows below each when checked. I would like it so that the select all check box also toggles these inputs. So the the issue is that after checking selectAll, it opens and closes each toggle about 5 times.
I believe it has something to do with the nested forloop inside my .each method, but not entirely sure.
Here's the code:
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');
}
}
});
}
});
Upvotes: 0
Views: 96
Reputation: 65808
Getting all the checkboxes at once is much simpler than you think
// Gather up all the checkboxes
var boxes = document.querySelectorAll("input[type=checkbox]");
And, making them all checked is also simple:
boxes.forEach(function(box){
box.setAttribute("checked","checked");
});
And, turning on the display of an associated element at the same time means adding just one line:
boxes.forEach(function(box){
box.setAttribute("checked","checked");
box.nextElementSibling.style.display = "inline";
});
And finally, tying all this to a "Select All" button:
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>
Upvotes: 1