Powered by Blogger.

Thursday, July 15, 2010

Checking / UnChecking all checkboxes of the page dynamically in a single click

Introduction
Generally we came acroos in this situation when we need to facilitate the user to select or delsect all records of the page at a single click instead of selecting records one by one.  You can refer to below picture for example.

Scenario
This generally happens when you are presenting some records into GridView or DataGrid and you are providing a column called Select, instead of checking all records one by one you want to provide links called "Select All" or  "DeSelect All" to check and uncheck all checkboxes of the GridView respectively.  
Solution
HTML Code
To do that you need to provide a two links as displayed in the picture above. Following is the code for "Select All" and "DeSelect All" link.
 
<a href="javascript:void(0)" onclick="SelectAllCheckBoxes(true)">Select Alla> | <a href="javascript:void(0)" onclick="SelectAllCheckBoxes(false)">DeSelect Alla>
If Select All link will be clicked then SelectAllCheckBoxes javascript function will fire with parameter as true and when DeSelect All link will be clicked the same function will fire with paramter as false.
JavaScript Code
The code for JavaScript function SelectAllCheckBoxes are as follows
<script language="javascript" type="text/javascript">
function SelectAllCheckBoxes(action)
{
   var myform=document.forms['aspnetForm'];
   var len = myform.elements.length;
   for( var i=0 ; i < len ; i++) 
   {
   if (myform.elements[i].type == 'checkbox') 
      myform.elements[i].checked = action;
   }
}
script> 
In the above function first I am getting the html form element in the myform variables then I am getting the length of all elements on the page. Next I am looping through all the elements and checking for the element whose element type is checkbox as I am only interested about the checkbox element of the page. Once I got the checkbox element I am assiging the checked property to the parameter passed to this function (either true or false) and I am done.
Thats it!!!
Conclusion
Doing this was simpler than I had expected, hope this helps some one. Thanks and Happy Coding !!!

by SheoNarayan

No comments:

Post a Comment

  ©Template by Dicas Blogger.

TOPO