advertisement -- please support sponsors

forms:
function get_radio_value

How can I determine which radio button on a form is checked?

Note: For an overview of what radio buttons are and how they work, please see the companion article, The Radio Object

All radio objects have a Boolean property named "checked" which can be read to determine whether or not the radio button is currently checked. To determine which radio button in a form is turned on, simply scan the array of Radio objects until one is found whose checked property is equal to true.

Here is a general function that accepts, as a parameter, a reference to a Radio object array, and returns the value of the checked radio button (or null if none of them is checked). You are free to use this code in your own web pages.

function get_radio_value (radio_array) { var i; for (i = 0; i < radio_array . length; ++ i) if (radio_array [i] . checked) return radio_array [i] . value; return null; }
Here is a form that uses get_radio_value to copy the value of the selected radio button into a text input field:
What is your favorite fruit?
apple
orange
banana
other

If you select a fruit and then click on the "echo" button, the value returned by the get_radio_value function will be copied into the text field.

Here is the source code for the form:

<form> What is your favorite fruit?<br> <input type=radio name=fruit value=apple>apple<br> <input type=radio name=fruit value=orange>orange<br> <input type=radio name=fruit value=banana>banana<br> <input type=radio name=fruit value=other>other <p> <input type=text name=echotext> <input type=button value=echo onClick="form . echotext . value = get_radio_value (form . fruit);"> </form>
As you can see, the parameter to the get_radio_value function is form . fruit, the Radio object array.

Charlton Rose
30 Jan. 1997