Thursday, January 15, 2009

(CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript

This question has been around for pretty long time.
Here is the Scenario; there is one TemplateColumn in GridView which is used to Select Row within GridView. So, there will be Checkbox inside ItemTemplate of that TemplateColumn. User would be able to select more than one Checkbox in that Column. And to Select All the Checkboxes of that column, there will be a "Select All" Checkbox in HeaderTemplate of that GridView. When user check "Select All" Checkbox in Header, all the checkboxes should be selected and vice versa And when an User will select all the checkbox individually the Select All checkbox should be selected and vice versa.

First of all I am showing the grid structure for this.










and Now the Required javascript for these.This one is for check/uncheck all Checkbox when Select All is clicked

function SelectAll(obj)
{
var item= <%=GridView1.Rows.Count%>;
if(obj.checked==true)
{
for(var i=2;i<=item+1;i++) { if(i<=9) document.getElementById("GridView1$ctl0"+i+"$chkChild").checked=true; else document.getElementById("GridView1$ctl"+i+"$chkChild").checked=true; } } else { for(var i=2;i<=item+1;i++) { if(i<=9) document.getElementById("GridView1$ctl0"+i+"$chkChild").checked=false; else document.getElementById("GridView1$ctl"+i+"$chkChild").checked=false; } } }

This one is for check/uncheck SelectAll Checkbox

function SelectParent(obj)
{ var item= <%=GridView1.Rows.Count%>;
var check=0;
for(var i=2;i<=item+1;i++)
{
if(i<=9)
{
if(document.getElementById("GridView1$ctl0"+i+"$chkChild").checked==true)
check++;
}
else
{
if(document.getElementById("GridView1$ctl"+i+"$chkChild").checked==true)
check++;
}
}
if(item==check)
document.getElementById("GridView1$ctl01$chkParent").checked=true;
else
document.getElementById("GridView1$ctl01$chkParent").checked=false;
}

No comments: