Checkbox Toggle Tutorial Select Deselect All Elements
Learn to toggle all html checkbox elements in a group on or off using JavaScript, or select any HTML elements by group when needed. You can select a class name with the getElementsByClassName() method to select a group by class, or you can select a group by name attribute using an array format and the getElementsByName() method. I will show both approaches below. When your form is processed you can use the name attribute in PHP to grab the array of selected items in the list($_POST["cbg1"] will be an array posted to PHP that you can break down in PHP).
<!DOCTYPE html>
<html>
<head>
<script>
function togglecheckboxes(master,group){
var cbarray = document.getElementsByClassName(group);
for(var i = 0; i < cbarray.length; i++){
var cb = document.getElementById(cbarray[i].id);
cb.checked = master.checked;
}
}
</script>
</head>
<body>
<input type="checkbox" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbgroup1')"> Toggle All
<br><br>
<input type="checkbox" id="cb1_1" class="cbgroup1" name="cbg1[]" value="1"> Item 1<br>
<input type="checkbox" id="cb1_2" class="cbgroup1" name="cbg1[]" value="2"> Item 2<br>
<input type="checkbox" id="cb1_3" class="cbgroup1" name="cbg1[]" value="3"> Item 3<br>
<input type="checkbox" id="cb1_4" class="cbgroup1" name="cbg1[]" value="4"> Item 4<br>
</body>
</html>
If you want to use the getElementsByName() method instead it is similar code:
<!DOCTYPE html>
<html>
<head>
<script>
function togglecheckboxes(master,group){
var cbarray = document.getElementsByName(group);
for(var i = 0; i < cbarray.length; i++){
cbarray[i].checked = master.checked;
}
}
</script>
</head>
<body>
<input type="checkbox" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbg1[]')"> Toggle All
<br><br>
<input type="checkbox" id="cb1_1" class="cbgroup1" name="cbg1[]" value="1"> Item 1<br>
<input type="checkbox" id="cb1_2" class="cbgroup1" name="cbg1[]" value="2"> Item 2<br>
<input type="checkbox" id="cb1_3" class="cbgroup1" name="cbg1[]" value="3"> Item 3<br>
<input type="checkbox" id="cb1_4" class="cbgroup1" name="cbg1[]" value="4"> Item 4<br>
</body>
</html>