Solution:2
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:
- <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>