Phmadala’s Weblog

Javascript to select one checkbox at a time inside a gridview containing checkbox as template column

Posted by: phmadala on: November 25, 2008

Many times we need javascript for controls inside a gridview.One such need is to check only one checkbox at a time.This code snippet illustrates how to do that and
this can be a guideline for all such needs.

The below javascript is for checkbox inside a gridview as template column.If one checkbox is selected, it should deselect other checkboxes .In code behind u have to include javascript for each checkbox in rowdatabound event.
  protected void dgprod_RowDataBound(object sender, GridViewRowEventArgs e)
    {
         CheckBox chkh = new CheckBox();
chkh=(checkbox)e.Row.FindControl(“chkcat”);
chkh.Attributes.Add(“onclick”, “javascript:return Selectone(this,’”+ dgprod.ClientID +”‘);”);

}

javascript to select one checkbox at a time:

function selectone(chid,gridviewid)
{

var grid=document.getelementbyid(“gridviewid”);
  for (i=1; i<grid.rows.length; i++)
                {
                        var inputs = grid.getElementsByTagName(“input”);
                        if (inputs.length>0)
                           {
//loop starts from 1. rows[0] points to the header.
                             for (i=1; i<inputs.length; i++) //if childNode type is CheckBox
                             {
                                  if(inputs[i].type==”checkbox”)
                                         {
                                       
                                              var chk=$get(inputs[i].id);
                                           
                                             if(chk.id!=chid.id)//checks the id of checkbox checked with other checkbox ids
{
chk.checked=false;
}

}
}

Leave a Reply

 

November 2008
M T W T F S S
« Oct   Dec »
 12
3456789
10111213141516
17181920212223
24252627282930

Visitors

  • 1,565 hits