In order to select all the checkboxes of a page, we need to create a selectAll () function through which we can select all the checkboxes together. In this section, not only we will learn to select all checkboxes, but we will also create another function that will deselect all the checked checkboxes.
We will implement and understand an example where we will create two buttons one for selecting all checkboxes and the other one for deselecting all the selected checkoxes. The example code is given below:
When we click on the 'Select All' button, we get:
When we deselect all checkboxes, we get:
- In the html body section, we have created four input types as Checkboxes and two more input types as button. For the input types as button, we have created one button for selecting the checkboxes where onClick (), the selects () function will be invoked and the other one for deselecting the checkboxes (if selected any/all) where onClick () the deselect () function will be invoked.
- So, when the user clicks on the 'Select All' button, it moves to the script section where it finds the selects () function and executes the statements within it.
- Similarly, when the user after selecting the checkboxes click on the "Deselect All" button, the deselect () function gets invoked. Also, if the user has selected a single or two checkboxes only, then also on clicking on the "Deselect All" button, it will deselect them. In case the user has not selected any checkbox and then clicking on the "Deselect All" button, no action will be shown or performed.
The user can create many such examples of using checkboxes and try out such function.
So, in this way the user can select all or deselect all checkboxes.