Sometimes, we may want to get the value of a selected radio button in our JavaScript web app.
In this article, we’ll look at how to get the value of a selected radio button with JavaScript.
Loop Through the Radio Buttons to Find the One with the checked Property set to true
We can select all the radio buttons in a group and get the radio button that has the checked
property set to true
.
For instance, we can write the following HTML:
<div id="fruits">
<input type="radio" name="fruit" value="apple"> Apple
<input type="radio" name="fruit" value="orange"> Orange
<input type="radio" name="fruit" value="grape" checked="checked"> Grape
</div>
Then we can get all the radio button elements with document.querySelectorAll
and get the one that’s checked by writing:
const fruits = document.querySelectorAll('input[name="fruit"]')
for (const f of fruits) {
if (f.checked) {
console.log(f.value)
}
}
fruits
is an HTMLCollection object with all the radio button elements.
Then we use for-of to loop through the radio buttons.
In the loop body, we get the checked
property of the radio button.
And we log the value of the one that’s checked.
Therefore, we should see 'grape'
logged.
Use the :checked Selector
Another way to get the radio button that’s checked is to use the :checked
selector.
For instance, we can write:
const selected = document.querySelector('input[name="fruit"]:checked').value;
console.log(selected)
to do this.
The input[name=”fruit”]:checked
selector gets all the inputs with the attribute name fruit
that is selected.
And we get the value
attribute’s value with the value
property.
So the value of selected
should be 'grape'
.
Get the Checked Value from the Form Values
We can also get the checked value of a radio button from the form values.
For instance, we can write:
<form id="fruits">
<input type="radio" name="fruit" value="apple"> Apple
<input type="radio" name="fruit" value="orange"> Orange
<input type="radio" name="fruit" value="grape" checked="checked"> Grape
</form>
Then we get the radio button that’s checked by writing:
const form = document.getElementById("fruits");
console.log(form.elements["fruit"].value);
We get the form element with getElementById
.
Then we get the inputs with the name attribute set to fruit
with form.elements[“fruit”]
.
And then we can get the value
property to get the selected value.
So console log should log 'grape'
.
Conclusion
There are several ways to get the checked value of a radio button with JavaScript.