Sunday, January 10, 2010

Select single Radio in DataGrid using JavaScript

some times we need to select a single row from a grid and for that we place a extra column in it. which contain a radio button in it. and we want that only one radio of that column should be selected. so to select single radio button in Grid using JavaScript (client side script) we need to write below code:

if your radio is 'runat="Server"' then below code will help you.
java Script function:

< script language="javascript" type="text/javascript" >
function selectOne(rdoId,gridName)
{
var rdo = document.getElementById(rdoId);
/* Getting an array of all the "INPUT" controls on the form.*/
var all = document.getElementsByTagName("input");
for(i=0;i< all.length;i++)
{
/*Checking if it is a radio button, and also checking if the
id of that radio button is different than "rdoId" */
if(all[i].type=="radio" && all[i].id != rdo.id)
{
var count=all[i].id.indexOf(gridName);
if(count!=-1)
{
all[i].checked=false;
}
}
}
rdo.checked=true;/* Finally making the clicked radio button CHECKED */
}

< /script >


Below is code for grid:
< asp:GridView ID="datagrid1" runat="server" AutoGenerateColumns="false" >
< Columns >
< asp:TemplateField HeaderText="Select" >
< ItemTemplate >
< asp:RadioButton id="rdobutton" runat="server" OnClick="javascript:selectOne(this.id,'datagrid1');" >< /asp:RadioButton > < /ItemTemplate >
< /asp:TemplateField >
< /Columns >
< /asp:GridView >




======If your radio is not run at server===========
If your radio is not run at server then you just need to make ID and Name field as a same value and thats sit.. nothing to do extra... you will be able to select only one of then..

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates