Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the SelectedValue of a RadioButtonList in JavaScript?

I have an ASP.NET web page with a databound RadioButtonList. I do not know how many radio buttons will be rendered at design time. I need to determine the SelectedValue on the client via JavaScript. I've tried the following without much luck:

var reasonCode = document.getElementById("RadioButtonList1");
var answer = reasonCode.SelectedValue;  

("answer" is being returned as "undefined") Please forgive my JavaScript ignorance, but what am I doing wrong?

Thanks in advance.

like image 774
Bob OMalley Avatar asked Feb 23 '09 22:02

Bob OMalley


People also ask

How to know which radio button is selected in JavaScript?

Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

How do I group radio buttons in HTML?

Defining Radio Group in HTML We can define a group for radio buttons by giving each radio button the same name. As and when the user selects a particular option from this group, other options are deselected. Following is an example of radio buttons with different names within a form.


1 Answers

ASP.NET renders a table and a bunch of other mark-up around the actual radio inputs. The following should work:-

 var list = document.getElementById("radios"); //Client ID of the radiolist
 var inputs = list.getElementsByTagName("input");
 var selected;
 for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].checked) {
          selected = inputs[i];
          break;
       }
  }
  if (selected) {
       alert(selected.value);
  }
like image 134
John Foster Avatar answered Sep 25 '22 15:09

John Foster