Radio Button Value
JavaScript can determine the value of a checked radio button — without code to test which of the radio button set is checked.
On a web page, when a radio button is checked, the button's value may trigger an image update or cause instructions to be updated. It may update the URL of a link or show a pertinent ad. The value may be sent to a script on the server with Ajax. A notice may be presented if the user checks a radio button with a certain value.
Sets of radio
button fields all have the same name. (But the values may differ.)
Here is an example set of radio buttons. Tapping on a radio button will check it, and also uncheck any previously checked buttons of the set.
Here is the source code.
<form name="MyForm" action="get"> <input type="radio" name="color" value="red"> Deep Red <input type="radio" name="color" value="white"> Brilliant White <input type="radio" name="color" value="gold"> Rich Gold </form>
The value of field name="color"
can be obtained with the JavaScript further below. The value will be the value of the radio button that is checked. (The name="MyForm"
also will be referred to in conjunction with the JavaScript.)
When none of the radio buttons in the set are checked, the value obtained with the JavaScript is a null string, a string variable with no characters.
If the checked radio button field has no value specified, the value is assumed to be "on". (The "on" value means "button check is turned on".)
Using JavaScript to get the value of the radio
button that is checked, without knowing in advance which button that will be, requires two things.
- A name for the
form
tag —name="MyForm"
in this case. - A name for the
radio
button set —name="color"
in this case.
Here is JavaScript to demonstrate how to obtain the value of the checked radio button.
<script type="text/javascript"> function GetCheckedValue() { var TheValue = document.forms["MyForm"]["color"].value; alert(TheValue); // Replace this line with code for functionality you want. } </script>
Change MyForm
and color
to the names of your form and your radio buttons, respectively. To demonstrate a use for the value, the JavaScript will launch an alert box with the checked radio button value. (The alert box code may be replaced with any code for the functionality you want.)
In the JavaScript, this part is what reads the value of the checked radio button.
document.forms["MyForm"]["color"].value
This "tap for checked radio button value" link will launch an alert box with the value of the radio button example near the beginning of this article.
Here is the code for the above link.
<a href="javascript:GetCheckedValue()"> tap for checked radio button value </a>
(This article first appeared with an issue of the Possibilities newsletter.)
Will Bontrager