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

13

17

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.

Plexor answered 23/2, 2009 at 22:10 Comment(0)
G
41

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);
  }
Gentlemanfarmer answered 23/2, 2009 at 22:35 Comment(4)
This answer works best if you don't know how many radio buttons you will have displayed on the page. Thanks!Plexor
I was really hoping for a more simpler answer, but I was unable to find anything betterSearch
thank you so much! helped me to stop my confusion :)Sos
not bad @john Foster. it helped me even after 11 yearsSedum
R
18

Try this to get the selected value from the RadioButtonList.

var selectedvalue = $('#<%= yourRadioButtonList.ClientID %> input:checked').val()
Recognizee answered 18/12, 2012 at 10:22 Comment(1)
He has asked for javascript. Jquery is far easier and shorter to write. You answer is of no help for people who are looking for doing this thru javascript. I am not downvoting your answer but stick to the question.Recourse
S
3

I always View Source. You will find each radio button item to have a unique id you can work with and iterate through them to figure out which one is Checked.

Edit: found an example. I have a radio button list rbSearch. This is in an ascx called ReportFilter. In View Source I see

ReportFilter1_rbSearch_0
ReportFilter1_rbSearch_1
ReportFilter1_rbSearch_2

So you can either loop through document.getElementById("ReportFilter1_rbSearch_" + idx ) or have a switch statement, and see which one has .checked = true.

Stillman answered 23/2, 2009 at 22:19 Comment(0)
S
1

RadioButtonList is an ASP.NET server control. This renders HTML to the browser that includes the radio button you are trying to manipulate using JavaScript.

I'd recommend using something like the IE Developer Toolbar (if you prefer Internet Explorer) or Firebug (if you prefer FireFox) to inspect the HTML output and find the ID of the radio button you want to manipulate in JavaScript.

Then you can use document.getElementByID("radioButtonID").checked from JavaScript to find out whether the radio button is selected or not.

Schock answered 23/2, 2009 at 22:13 Comment(0)
P
1

The HTML equivalent to ASP.NET RadioButtonList, is a set of <input type="radio"> with the same name attribute(based on ID property of the RadioButtonList).

You can access this group of radio buttons using getElementsByName. This is a collection of radio buttons, accessed through their index.

alert( document.getElementsByName('RadioButtonList1') [0].checked );
Prejudice answered 23/2, 2009 at 22:43 Comment(1)
I didn't know that - nice one!Stillman
F
1

For a 'RadioButtonList with only 2 values 'yes' and 'no', I have done this:

var chkval=document.getElemenById("rdnPosition_0")

Here rdnposition_0 refers to the id of the yes ListItem. I got it by viewing the source code of the form.

Then I did chkval.checked to know if the value 'Yes' is checked.

Fibrilla answered 7/7, 2010 at 10:18 Comment(1)
The OP said: 'I do not know how many radio buttons will be rendered at design time'--> So he can't use static id's like that, because you don't know how many elements there will be. Now _0 is 'Yes' but when you change the buttons, _0 can be 'No'. Bad solution for maintainabilityBukhara
G
1
function CheckRadioListSelectedItem(name) {

    var radioButtons = document.getElementsByName(name);
    var Cells = radioButtons[0].cells.length;

    for (var x = 0; x < Cells; x++) {
        if (document.getElementsByName(name + '_' + x)[0].checked) {
            return x;
        }
    }

    return -1;
}
Gaussmeter answered 22/12, 2011 at 8:34 Comment(0)
E
1

I would like to add the most straightforward solution to this problem:

var reasons= document.getElementsByName("<%=RadioButtonList1.UniqueID%>");
var answer;
for (var j = 0; j < reasons.length; j++) {
    if (reason[j].checked) {
        answer = reason[j].value;
    }
}

UniqueID is the property that gave you the name of the inputs inside the control, so you can just check them really easily.

Exponent answered 28/2, 2013 at 10:11 Comment(1)
Awesome, this worked nicely for me, have been struggling with this for some time now, had problems finding my radiobuttonlist-control because it was inside a ContentPlaceHolder which messes the ID on rendering. By setting the ID with use of UniqueID worked perfectly. Thanks.Algonquin
E
1

I've tried various ways of determining a RadioButtonList's SelectedValue in Javascript with no joy. Then I looked at the web page's HTML and realised that ASP.NET renders a RadioButtonList control to a web page as a single-column HTML table!

<table id="rdolst" border="0">
  <tr>
    <td><input id="rdolst_0" type="radio" name="rdolst" value="Option 1" /><label for="rdolst_0">Option 1</label></td>
  </tr>
  <tr>
    <td><input id="rdolst_1" type="radio" name="rdolst" value="Option 2" /><label for="rdolst_1">Option 2</label></td>
  </tr>
</table>

To access an individual ListItem on the RadioButtonList through Javascript, you need to reference it within the cell's child controls (known as nodes in Javascript) on the relevant row. Each ListItem is rendered as the first (zero) element in the first (zero) cell on its row.

This example loops through the RadioButtonList to display the SelectedValue:

var pos, rdolst;

for (pos = 0; pos < rdolst.rows.length; pos++) {
    if (rdolst.rows[pos].cells[0].childNodes[0].checked) {
        alert(rdolst.rows[pos].cells[0].childNodes[0].value);
        //^ Returns value of selected RadioButton
    }
}

To select the last item in the RadioButtonList, you would do this:

rdolst.rows[rdolst.rows.length - 1].cells[0].childNodes[0].checked = true;

So interacting with a RadioButtonList in Javascript is very much like working with a regular table. Like I say I've tried most of the other solutions out there but this is the only one which works for me.

Erhart answered 4/10, 2013 at 1:23 Comment(0)
Q
0
reasonCode.options[reasonCode.selectedIndex].value
Quizmaster answered 23/2, 2009 at 22:13 Comment(1)
Are you sure that reasonCode will actually contain the form field? I would expect it to be the outer container element of the RadioButtonList.Torino
I
0

I wanted to execute the ShowShouldWait script only if the Page_ClientValidate was true. At the end of the script, the value of b is returned to prevent the postback event in the case it is not valid.

In case anyone is curious, the ShouldShowWait call is used to only show the "please wait" div if the output type selected is "HTML" and not "CSV".

onclientclick="var isGood = Page_ClientValidate('vgTrxByCustomerNumber');if(isGood){ShouldShowWait('optTrxByCustomer');} return isGood"
Influx answered 7/9, 2016 at 18:50 Comment(0)
S
0

To check the selected index of drop down in JavaScript:

function SaveQuestion() {
    var ddlQues = document.getElementById("<%= ddlQuestion.ClientID %>");
    var ddlSubQues = document.getElementById("<%=ddlSecondaryQuestion.ClientID%>");

    if (ddlQues.value != "" && ddlSubQues.value != "") {
        if (ddlQues.options[ddlQues.selectedIndex].index != 0 ||
            ddlSubQues.options[ddlSubQues.selectedIndex].index != 0) {
            return true;
        } else {
            return false;
        }
    } else {
        alert("Please select the Question or Sub Question.");
        return false;
    }
}
Stereometry answered 28/2, 2019 at 7:19 Comment(0)
S
-2

From here:

if (RadioButtonList1.SelectedIndex > -1) 
{
    Label1.Text = "You selected: " + RadioButtonList1.SelectedItem.Text;
}
Sublieutenant answered 23/2, 2009 at 22:24 Comment(1)
Those code samples are server side "runat=server". He's looking for client side code, which of course doesn't follow the ASP.NET object model.Apomict

© 2022 - 2024 — McMap. All rights reserved.