Friday, May 26, 2006

RadioButtonList Javascript Accessible

{

I recently was trying to write some javascript that interacted with the ASP.NET 2.0 RadioButtonList. My first attempts at obtaining a handle to the control via document.getElementById were successful but unsuccessful. Successful in that they weren't giving me a "null" reference back, but unsuccessful in that I was not getting the selected value of the radio buttons.

It turns out the RadioButtonList is rendered as an HTML Table element, with the table getting the corresponding id of the server control and the radio buttons getting id values that had an increment on the end. Their name attribute, which groups them, was the same as the RadioButtonList id.

Simple example: you have a RadioButtonList you give an id of myList. ASP.NET 2.0 renders a table with the id attribute of "myList." You'll have your radio buttons inside, named myList_0, myList_1, and so on. These radio buttons, rendered as getElementsByTagName("input") to get your radio buttons. Test to see which is selected and you're all done. The following function encapsulates that logic, and we've begun reusing it all over the place. The radioList argument should just be the ClientId of your RadioButtonList:

function getRadioSelectedValue(radioList){
var options = radioList.getElementsByTagName('input');
for(i=0;i<options.length;i++){
var opt = options[i];
if(opt.checked){
return opt.value;
}
}
}

}

13 comments:

Andrew said...

Thanks David, this was very helpful.

Julien said...

Great tip!
The perfect answer to what I was looking for

lokesh said...

Thanks for nice solution
Good job

Nitin said...

Thanks, nice solution for accessing radioButtonList in javascript

Khurram said...

Hi David

Thanks for the solution, saved me from pulling my every hair out.

Tigris said...

Thank you!!! I've been searching high and low for this answer (albeit for a databound checkboxlist). Works like a champ!

Tigris said...

One thousand Thanks!!! I've been searching high and low for this answer (albeit for a databound checkboxlist). Works like a champ!

Yazılım Mühendisleri said...

Thanks David. in Turkey

robgonsalves said...

You 'da man!

Rob in Boston

Emanuele said...

Thanks for the solution!

ilan said...

thanks for the helpfull post.
just to clear 1 thing, u said that the"radioList" is the id of the radio object, but it must be the client elemnet itself.
in case the user want to send only the client id, the first line of the function must change to:
var options = document.getElementById(radioList).getElementByTagName etc..

Shailendra said...

hey good tips to solve d problem!!

Pix said...

Great Help !!