'checking'에 해당되는 글 1건

  1. 2009.05.20 Checking / UnChecking all checkboxes of the page dynamically in a single click
2009. 5. 20. 10:16

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

출처 : http://www.dotnetfunda.com/articles/article85.aspx

화면 상의 모든 체크 박스를 단일 클릭으로 모두 Checking, UnChecking 하는 JavaScript
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 All</a> | <a href="javascript:void(0)" onclick="SelectAllCheckBoxes(false)">DeSelect All</a>

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 !!!