Finding the value of a radio button

Finding the value of a radio button cover image
  1. Home
  2. HTML
  3. Finding the value of a radio button

The name and value for all HTML form elements can be set using the respective attributes. In case of a text field and textareas, the value can be explicitly displayed on the screen. It’s also very easy to access such values.
For example, document.orderform.email_add.value determines the value of email_add text field present in orderform.

Accessing the value for a set of radio buttons is not that straight forward. document.form_name.radio_name.value does not work. (Both Nescape and Internet Explorer return “undefined” as value).

Sponsored Links

The solution is to iterate through all the radio buttons in that set (radio buttons having the same name) and then extract the value from the button that is checked.

<form name="orderform">
Which one is your favorite?<br>
<input type="radio" name="music" value="Rock" 
checked="checked"> Rock<br>
<input type="radio" name="music" value="Reggae"> Reggae<br>
<input type="radio" name="music" value="Pop"> Pop<br>
<input type="radio" name="music" value="Rap"> Rap<br>
<input type="radio" name="music" value="Metal"> Metal<br>
<input type="submit" onclick="get_radio_value()">
</form>

orderform above contains a set of five radio buttons called music. To get the associated value, we’ll use the following code:

<script type="text/javascript">
<!--

function get_radio_value()
{
for (var i=0; i < document.orderform.music.length; i++)
   {
   if (document.orderform.music[i].checked)
      {
      var rad_val = document.orderform.music[i].value;
      }
   }
}

//-->
</script>

document.orderform.music.length determines the number of radio buttons with the name music. In our case, we can substitute this with 5, since we already know the number. The for loop iterates through all the radio buttons in that set and determines which of these is checked using an If statement. Once a checked radio button is found, its value is stored in a variable.
This code can be placed inside the HTML Head section or an external .js file containing JavaScript code.

Click here to see how the code works

HTML JavaScript