Automatically have all checkboxes selected on page load

Solution:1

on HTML just add checked as attribute for input type="checkbox"

 

<input type="checkbox" name="test1" value="test1" checked> I'm Check<br>
<input type="checkbox" name="test2" value="test2" checked> I'm Check<br>
<input type="checkbox" name="test3" value="test3"> I'm not Check<br>
<input type="checkbox" name="test4" value="test4" checked> I'm Check

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:

  1. <html>
  2. <head>
  3.         <title>Selecting or deselecting all CheckBoxes</title>
  4.         <script type=“text/javascript”>
  5.             function selects(){
  6.                 var ele=document.getElementsByName(‘chk’);
  7.                 for(var i=0; i<ele.length; i++){
  8.                     if(ele[i].type==’checkbox’)
  9.                         ele[i].checked=true;
  10.                 }
  11.             }
  12.             function deSelect(){
  13.                 var ele=document.getElementsByName(‘chk’);
  14.                 for(var i=0; i<ele.length; i++){
  15.                     if(ele[i].type==’checkbox’)
  16.                         ele[i].checked=false;
  17.                 }
  18.             }
  19.         </script>
  20.     </head>
  21. <body>
  22.     <h3>Select or Deselect all or some checkboxes as per your mood:</h3>
  23.     <input type=“checkbox” name=“chk” value=“Smile”>Smile<br>
  24.     <input type=“checkbox” name=“chk” value=“Cry”>Cry<br>
  25.     <input type=“checkbox” name=“chk” value=“Laugh”>Laugh<br>
  26.     <input type=“checkbox” name=“chk” value=“Angry”>Angry<br>
  27.      <br>
  28.         <input type=“button” onclick=‘selects()’ value=“Select All”/>
  29.         <input type=“button” onclick=‘deSelect()’ value=“Deselect All”/>
  30.       </body>
  31. </html>