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, TheRadio
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.
Here is a form that usesfunction 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; }
get_radio_value
to copy the value of the selected radio button into a text input field:
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:
As you can see, the parameter to the
get_radio_value
function is form . fruit
, the Radio
object array.
Charlton Rose
30 Jan. 1997