Get relavated value of selected row of GridView using javascipts

2008-04-30


(from: http://geekswithblogs.net/azamsharp/archive/2006/08/29/89697.aspx) So, here is the story. I have a GridView which contains the ASP.NET CheckBox control. Each row also have the primary key of the database table. Now, I need to get the ID of the selected checkbox using JavaScript. I used a hidden field to store the ID of the row (The row is hidden and the user cannot see it on the display but you can see the value if you do the view source). Now, I like to access the hidden field of the selected row of the GridView.

<asp:TemplateField>

<ItemTemplate>

<asp:CheckBox id="chkSelect" runat="server" />

<asp:HiddenField ID="hfID" runat="server" Value='<%# Eval("ID") %>' />

</ItemTemplate>

</asp:TemplateField>

And here is the JavaScript code:

function GetIDFromHiddenField()

{

var elements = document.getElementsByTagName("INPUT");

var ID;

var count = 0;

for(i=0; i< elements.length; i++)

{

if(elements[i].type == 'checkbox')

{

if(elements[i].checked == true)

{

count = count + 1;

ID= elements[i].nextSibling.nextSibling.value;

}

}

}

// check if more then one exam is selected. If so, then alert the user

if(count > 1) { alert('Please only select a single item from the list'); return (-1); }

else return ID;

}

Althought I am only allowing the user to select a single item I am sure you got the basic idea.