Radio buttons are used whenever you want a user to choose only one option out of the given options. On the other hand, the checkboxes are used when a user can choose single or multiple options out of given options.
Toggling the state of a single checkbox is easy, but to do the same for multiple checkboxes can be a little tricky. We will use the forEach() loop and checked property to accomplish our goal.
In the following example, we have multiple checkboxes. Depending upon the state of the first checkbox, we will check or uncheck rest of the checkboxes. Please have a look over the code example and the steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, input, and label).
The div element is just a wrapper for the rest of the elements. We are using style attribute just to center align all elements horizontally.
The first checkbox has a label of “All”. Depending upon the state of this checkbox, we will toggle the state of the rest of the checkboxes.
We have selected the first checkbox using the document.getElementById () method and stored it in all variable.
We have attached the click event listener to it.
We have toggle() method and this method will act as our event handler function.
In the toggle() method, we are getting the state of the first checkbox and storing it in the isChecked variable. This variable holds a Boolean value. For checked, it will be true and for unchecked, it will be false.
We have selected all the checkboxes using the document.getElementsByTagName() method. This method returns a node list.
We are converting that node list into an array by using the Array.from() method.
We are using the forEach() loop to loop through each element in the array. Inside the loop, we are assigning the value of isChecked variable to the checked property of each element.
We are attaching click event listener to rest of the checkboxes by using document.querySelectorAll(), Array.from() and forEach() loop.
The event handler function is the uncheckAll() method. Inside this method, we are simply unchecking the first checkbox by setting its checked property to false.
const all = document.getElementById('all');
const isChecked = all.checked;
element.checked = isChecked;
all.checked = false