I have a series of checkboxes generated with PHP, and it uses JavaScript to show/hide elements based on when they are selected/deselected. This works just fine. Now I'm trying to add a select all checkbox, and I'm having difficulty. So far, I got it to work where it will select all of the checkboxes, but it doesn't fire all of the elements to show or hide. The checkboxes just get checked or unchecked and nothing else happens. Here is my code:
$results .= '<div class="tools-tag-filter-container">';
$results .= '<div class="tools-tag-selection">
<input type="checkbox" id="tools-tag-checkbox-selectall" onclick="toggleTags(this)">
<span class="tools-tag-checkbox-label">
<label for="tools-tag-checkbox-selectall"><strong>Select All</strong></label>
</span>
</div>';
foreach ($displayed_tags as $displayed_tag){
$results .= '<div class="tools-tag-selection">
<input type="checkbox" id="tools-tag-checkbox-'.$displayed_tag->slug.'"
name="tools-filter-checkboxes" value="'.$displayed_tag->slug.'"
onclick="showHideTag("'.$displayed_tag->slug.'")">
<span id="tools-label-'.$displayed_tag->slug.'" class="tools-tag-checkbox-label">
<label for="tools-tag-checkbox-'.$displayed_tag->slug.'">'.$displayed_tag->name.'</label>
</span>
</div>';
}
$results .= '<script type="text/javascript">
function showHideTag(slug) {
var checkBox = document.getElementById("tools-tag-checkbox-" + slug);
var section = document.getElementById("tools-tag-section-" + slug);
var label = document.getElementById("tools-label-" + slug);
if (checkBox.checked == false){
section.style.display = "none";
label.classList.remove("label-selected");
} else {
section.style.display = "block";
label.classList.add("label-selected");
}
}
function toggleTags(source) {
var checkboxes = document.getElementsByName("tools-filter-checkboxes");
for(var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
</script>';
$results .= '</div><div class="clear-both"></div>';
I tried firing the functions in the toggleTags() function as shown below, but that only selects the first checkbox and doesn't display/hide the element. I also get this error in the console log: "Uncaught TypeError: Cannot read property 'checked' of null".
function toggleTags(source) {
var checkboxes = document.getElementsByName("tools-filter-checkboxes");
for(var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
showHideTag("""+checkboxes[i].value+"""); // <--
}
}
Aucun commentaire:
Enregistrer un commentaire