How to toggle between one checkbox and a whole group of checkboxes in HTML ?
Given an HTML document having one checkbox and a group of checkboxes and the task is to toggle between them with the help of JavaScript.
We can achieve this by using the event onChange() which is triggered whenever we check or uncheck the checkbox.
We can pass a function to this event which should uncheck all the checkboxes in the group using forEach loop, if the separate checkbox is checked and should also uncheck the separate the checkbox whenever we check any of the checkboxes in the group.
Syntax:
let groupCheck = Array.from(document.getElementsByName('group')) let sepCheck = document.getElementById('sep') groupCheck.forEach(element => { element.onchange = () => { if (element.checked) { sepCheck.checked = false; } } }) sepCheck.onchange = () => { if (sepCheck.checked) { groupCheck.forEach(element => { element.checked = false; }) } }}
Example:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title > How to toggle between one checkbox and a whole group of checkboxes? </ title > < style > body { text-align: center; margin-top: 30%; } h1 { color: green; } p { margin-top: 4%; } label { margin-left: 3%; } </ style > </ head > < body > < h1 >GeeksforGeeks</ h1 > < h4 > How to toggle between one checkbox and a whole group of checkboxes? </ h4 > < p > < label for = "one" >< input type = "checkbox" name = "group" id = "one" />First </ label > < label for = "two" >< input type = "checkbox" name = "group" id = "two" />Second </ label > < label for = "three" >< input type = "checkbox" name = "group" id = "three" />Third </ label > </ p > < p > < label for = "sep" >< input type = "checkbox" name = "sep" id = "sep" />Separate </ label > </ p > < script > // Returns an array of all the // checkboxes in the group let groupCheck = Array.from( document.getElementsByName('group')) // Returns the separate checkbox let sepCheck = document.getElementById('sep') groupCheck.forEach(element => { // Setting onChange event for every // checkbox in the group element.onchange = () => { if (element.checked) { // Unchecking the checkbox sepCheck.checked = false; } } }) // Setting onChange event for the // separate checkbox sepCheck.onchange = () => { if (sepCheck.checked) { groupCheck.forEach(element => { // Unchecking the checkbox element.checked = false; }) } } </ script > </ body > </ html > |
Output: