Introduction
Very often, we face a situation where we have placed checkboxes inside any data control like repeater, datagrid, gridview, datalist, etc. and we want to perform all the check, uncheck actions on the client side. Here is the solution using JavaScript. Note: Different data controls may need some changes. Here, I have carried out my work on GridView.
Background
To use this code, we should have a basic knowledge of JavaScript, i.e.
- How the function is defined?
- How the parameter in the function is passed and used?
- How the variable is defined?
Using the Code
The example I have posted here is fully functional, but as I have stated earlier I have used GridView. However, the code is compatible with any DataControl available in ASP.NET. All we need is to change the parameter that we are passing on the ClientClick of the CheckBox in HeaderRow and CheckBox in ItemRow.
function check(DataControlName,ChildCheckBoxName)
{
var chkbox;
var i=2;
var c=2;
var u=2;
chkbox = document.getElementById(DataControlName +
'_ctl0' + i + '_' + ChildCheckBoxName);
while(chkbox!=null)
{
if(chkbox.checked==true)
c=c+1;
else
u=u+1;
i=i+1;
chkbox = document.getElementById(DataControlName +
'_ctl0' + i + '_' + ChildCheckBoxName);
}
chkbox=document.getElementById("GridView1_ctl01_chbxHeader");
if(i==c)
{
chkbox.checked = true;
}
if(i==u)
{
chkbox.checked = false;
}
if(i!=c)
chkbox.checked = false;
}
function SelectOrUnselectAll_DC_CheckBox(DataControlName,obj,ChildCheckBoxName)
{
if(obj.checked==true)
{
SelectAll_DC_CheckBox(DataControlName,ChildCheckBoxName);
}
else
{
UnselectAll_DC_CheckBox(DataControlName,ChildCheckBoxName);
}
}
function SelectAll_DC_CheckBox(DataControlName,objid)
{
var chkbox;
var i=2;
chkbox=document.getElementById(DataControlName + '_ctl0' + i + '_' + objid);
while(chkbox!=null)
{
chkbox.checked=true;
i=i+1;
chkbox=document.getElementById(DataControlName + '_ctl0' + i + '_' + objid);
}
}
function UnselectAll_DC_CheckBox(DataControlName,objid)
{
var chkbox;
var i=2;
chkbox=document.getElementById(DataControlName + '_ctl0' + i + '_' + objid);
while(chkbox!=null)
{
chkbox.checked=false;
i=i+1;
chkbox=document.getElementById(DataControlName + '_ctl0' + i + '_' + objid);
}
}
How To Call These Functions?
If the CheckBox is placed in <HeaderTemplate>, we call the function as follows:
onclick="SelectOrUnselectAll_DC_CheckBox('GridView1',this,'chbxChild')"
If the CheckBox is placed in <itemtemplate>, we call the function as follows:
onclick="check('GridView1','chbxChild')"
History
- 26th January, 2009: Initial post