|
|
Finding the value of a radio buttonThe 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. 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). <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. Check the results
Page contents: JavaScript code for finding the value associated with a web page HTML form radio button and how to use it for form processing.
Page URL: http://www.webdevelopersnotes.com/tips/html/ finding_the_value_of_a_radio_button.php3
|
|