How to select all checkboxes using JavaScript

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.

So, let's see how we can check and uncheck all the checkboxes in a JavaScript code.

Selecting all checkboxes in a JavaScript code

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:

Output:

When we click on the 'Select All' button, we get:

How to select all checkboxes using JavaScript

When we deselect all checkboxes, we get:

How to select all checkboxes using JavaScript

Code Explanation

  1. The above complete code is based on HTML and JavaScript.
  2. 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.
  3. 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.
  4. 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.






Contact US

Email:[email protected]

How to select all checkboxes using JavaScript
10/30