Check Uncheck All Checkboxes in Html Using JavaScript

One of the most common javascript needs for a webpage which shows data in a table is to provide a facility to select a row of data via a checkbox. On top of such rows of data a “Select All” or “Unselect All” checkbox is provided. Checking of this global checkbox checks all row level checkboxes and unchecking of the global checkbox unchecks all row-level ones. The code below is a sample Check/Uncheck All implementation using java script –

<html>
 <head>
  <script type="text/javascript">function CheckUncheckAll(){
   var  selectAllCheckbox=document.getElementById("checkUncheckAll");
   if(selectAllCheckbox.checked==true){
    var checkboxes =  document.getElementsByName("rowSelectCheckBox");
     for(var i=0, n=checkboxes.length;i<n;i++) {
      checkboxes[i].checked = true;
     }
    }else {
     var checkboxes =  document.getElementsByName("rowSelectCheckBox");
     for(var i=0, n=checkboxes.length;i<n;i++) {
      checkboxes[i].checked = false;
     }
    }
   }</script>
  </head>
 <body>
  <form id="form1" action="dummyAction" method="get">
   <table colspan="2" width="500" border="1" align="left" cellpadding="0" cellspacing="0">
    <tr bgcolor="#ABB">
     <td><input type="checkbox" id="checkUncheckAll" onClick="CheckUncheckAll()"/></td><td >Employee Name</td>
    </tr>
    <tr>
     <td><input type="checkbox" name="rowSelectCheckBox" value="1" onClick="CheckUncheckAll()"/></td><td>John Doe</td>
    </tr>
    <tr>
     <td><input type="checkbox" name="rowSelectCheckBox" value="2" onClick="CheckUncheckAll()"/></td><td>Mr Black</td>
    </tr>
   </table>
  </form>
 </body>
</html>

Detailed explanation of the above html code follows

  1. There is a ‘Select All’ checkbox which has the id ‘checkUncheckAll’.
  2. Every individual record or row in the tabular data has a checkbox for that row. The ‘value’ field contains the unique identifier for each row which will be needed at the server side when this form is submitted. This row-level checkbox has the name ‘rowSelectCheckBox’.
  3. When the ‘Select All’ checkbox is clicked the ‘CheckUncheckAll()’ java script method is called.
  4. The CheckUncheckAll() javascript method does the following –
    i. The Select All element is loaded into a variable called ‘selectAllCheckbox’.
    ii. It is then checked through an if-then-else statement if the checkbox referenced by selectAllCheckbox is checked or unchecked
    iii. If the Select All checkbox is found to be checked then the code retrieves the references to all row-level checkboxes and sets them to checked
    iv. Else, if the Select All checkbox is found to be unchecked then the code retrieves the references to all row-level checkboxes and sets them as unchecked.

 

Digiprove sealCopyright © 2014-2019 JavaBrahman.com, all rights reserved.