Finding the value of a radio button

Author: satz | Date: September 29, 2009

Accessing the value of a radio button set is not an easy task. Values from text input fields can be easily retrieved easily by just making use of [document.formname.textinputfiledname.value]. But radio button set’s value cannot be retrieved using this method.

This article shows how to get the value of a radio button set.

<form name="formname" method="post" onsubmit="getRadioButtonValue();">
 Which is your favorite color? <br><br>
 <input type="radio" name="color" value="RED"
 checked="checked"> RED<br>
 <input type="radio" name="color" value="YELLOW"> YELLOW<br>
 <input type="radio" name="color" value="WHITE">WHITE<br>
 <input type="radio" name="color" value="GREEN">GREEN<br>
 <input type="radio" name="color" value="BLUE">BLUE<br>
 <input type="submit" value="get the radio button value">
 </form>

The following function will fetch the value from the above form.

<script type="text/javascript">
 <!--
 function getRadioButtonValue()
 {
 for (var i=0; i < document.formname.color.length; i++)
 {
 if (document.formname.color[i].checked)
 {
 var color_val = document.formname.color[i].value;
 }
 }
 alert(color_val);
 }
 //-->
 </script>

Function Explained:

The function ‘getRadioButtonValue()’, loops through each of the radio buttons to see if it is checked or not. When the loop reaches the  checked one that particular radio button’s value is stored into ‘color_val’ and then alerts it as the selected color.