To begin, start by creating your form and assigning a class to group elements
<form name="my_form" id="my_form">
<h1>Types of Animals</h1>
<input type="checkbox" value="" id="all_animals" /> Select All <br />
<input type="checkbox" value="Dog" class="animals" /> Dog <br />
<input type="checkbox" value="Cat" class="animals" /> Cat
<h1>Colors</h1>
<input type="checkbox" value="" id="all_colors" /> Select All <br />
<input type="checkbox" value="Red" class="colors" /> Red <br />
<input type="checkbox" value="Blue" class="colors" /> Blue
</form>
Next, implement an unobtrusive function to handle the specified actions
function ToggleCheck() {
var allAnimals = document.getElementById('all_animals'),
allColors = document.getElementById('all_colors'),
formElements = document.forms.my_form.elements;
allAnimals.onclick = function() { // add a click event for the first group (animals)
if (allAnimals.checked) { // if SELECT ALL is clicked
for (var i = 0; i < formElements.length; i++) { // iterate over all form elements
if ( formElements[i].type === 'checkbox' && formElements[i].className === 'animals' ){ // check if checkbox belongs to animals group
formElements[i].checked = true; // mark it as checked
}
}
}
else { // if SELECT ALL is unchecked
for (var i = 0; i < formElements.length; i++) { // loop over all form elements
if ( formElements[i].type === 'checkbox' && formElements[i].className === 'animals' ) { // check if checkbox belongs to animals group
formElements[i].checked = false; // unmark it
}
}
}
};
// handle the same logic for colors
allColors.onclick = function() {
if(allColors.checked){
for (var i = 0; i < formElements.length; i++) {
if ( formElements[i].type === 'checkbox' && formElements[i].className === 'colors' ){
formElements[i].checked = true;
}
}
}
else {
for (var i = 0; i < formElements.length; i++) {
if ( formElements[i].type === 'checkbox' && formElements[i].className === 'colors' ){
formElements[i].checked = false;
}
}
}
};
}
window.onload = ToggleCheck; // execute the function upon page load