Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.

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.

 

 

 

Posted on Tuesday, August 29, 2006 1:36 PM | Back to top


Comments on this post: Get ID of the database table of the selected row of GridView using checkbox

# re: Get ID of the database table of the selected row of GridView using checkbox
Requesting Gravatar...
Hi,

The code is very useful as it is short n simple, I'm new in javascript thingy..

I have a slight problem tho..

how to get the Text value of the selected checkedbox list? because youre solution returns only the value.

Thanks;
Left by dani on Jan 23, 2007 1:48 AM

# re: Get ID of the database table of the selected row of GridView using checkbox
Requesting Gravatar...
The same thing you can achieve by using Datakeyname property of GridView
Left by Rana on Oct 23, 2007 4:07 PM

# re: Get ID of the database table of the selected row of GridView using checkbox
Requesting Gravatar...
<script>window.alert('you should watch out for XSS')</script>
Left by XSS on Jan 28, 2008 10:12 AM

# re: Get ID of the database table of the selected row of GridView using checkbox
Requesting Gravatar...
It's so simple and effient. Just love it.
Left by sophia on May 12, 2008 5:09 PM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net