To enable the selection of all checkboxes on a webpage, we must develop a selectAll function that allows us to check all the checkboxes simultaneously. In this segment, we will not only explore the process of selecting all checkboxes but also implement an additional function designed to uncheck all currently selected checkboxes.
Now, let's explore the method to select and deselect all checkboxes using JavaScript code.
Selecting all checkboxes in a JavaScript code
In this section, we will develop and comprehend an example that includes the creation of two buttons: one designated for selecting all checkboxes and another intended for unselecting all currently checked checkboxes. The code for this example is provided below:
<html>
<head>
<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++){
if(ele[i].type=='checkbox')
ele[i].checked=true;
}
}
function deSelect(){
var ele=document.getElementsByName('chk');
for(var i=0; i<ele.length; i++){
if(ele[i].type=='checkbox')
ele[i].checked=false;
}
}
</script>
</head>
<body>
<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>
<br>
<input type="button" onclick='selects()' value="Select All"/>
<input type="button" onclick='deSelect()' value="Deselect All"/>
</body>
</html>
Output:
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 has the ability to generate numerous instances of utilizing checkboxes and experiment with this functionality.
Thus, the user has the ability to either select all checkboxes or deselect all of them.