How to get the value of a selected radio button
To fetch the value of the selected radio button, simply run:
Ensure to replace groupName
with your radio button group's name. The use of the ?
operator shields against null values when no button is selected, effectively preventing errors. This one-liner retrieves and presents the value of the chosen radio button swiftly.
What about browser compatibility?
This method works like a charm with IE9+ and all modern browsers. Be careful not to call the .value
property on a div
, it's like asking a fish to climb a tree; swimming is to fish, as .value
is to radio inputs.
jQuery squad, where you at?
If you're part of the jQuery fan club, this elegant line has your back:
This does the same job but in jQuery style.
Check please!
To confirm if a radio button is selected or not, the .checked
property rides to the rescue:
This boolean expression helps ensure an option is selected before you proceed to the next step in your application logic.
Iterating the Node way
By looping through all radio buttons sharing the same name with document.getElementsByName('groupName')
and checking .checked
on each, you can work out which is selected:
This method ensures that no radio button gets left out!
The element of forms
You can retrieve the value by leveraging form elements' properties:
If you're navigating through a jungle of form controls, cling to the elements
collection.
Advanced radio broadcasting
For the advanced out there working with complex forms, meet the RadioNodeList
, your new BFF for browsers like Firefox 33+:
Here, document.forms['myForm']
refers to your form by name or ID, and ['groupName']
is the name of your radio button group.
Beware of the undefined
In cases where no radio button is selected, the value
could return undefined
. To prevent your app from throwing a fit, sprinkle in some validation checks or set a default selection.
Was this article helpful?