Website Design Edmonton       Website Design Feedback       Website Design Sitemap     Contact Website Design Company
Website Designers R Us - Home
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).
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> 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 LANGUAGE="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.

Return to Listing

Website Designers R Us is a professional Internet strategy and Web design company based in Toronto, Canada. We specialize in best-in-class website design, online marketing, Flash multimedia, corporate identity and print graphics. Website Designers R Us features an integrated team of web consultants, creative designers, writers, programmers and marketing professionals that know how to get online results
 Home          ::             About Us          ::             Support            ::             Services            ::             Link Partners          ::             Contact

Copyright © 2006-2011 Website Designers R Us, a DOT Specialist Company. All rights reserved.