Javascript – How to select all checkboxes using JavaScript – Javascript Tutorial

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:

        <title>Selecting or deselecting all CheckBoxes</title>  
        <script type="text/javascript">  
            function selects(){  
                var ele=document.getElementsByName('chk');  
                for(var i=0; i<ele.length; i++){  
            function deSelect(){  
                var ele=document.getElementsByName('chk');  
                for(var i=0; i<ele.length; i++){  
    <h3>Select or Deselect all or some checkboxes as per your mood:</h3>  
    <input type="checkbox" name="chk" value="Smile">Smile<br>  
    <input type="checkbox" name="chk" value="Cry">Cry<br>  
    <input type="checkbox" name="chk" value="Laugh">Laugh<br>  
    <input type="checkbox" name="chk" value="Angry">Angry<br>  
        <input type="button" onclick='selects()' value="Select All"/>  
        <input type="button" onclick='deSelect()' value="Deselect All"/>  


When we click on the ‘Select All’ button, we get:

When we deselect all checkboxes, we get:

Code Explanation

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