How to Get the Selected Radio Button Value in JavaScript
A group of radio buttons in HTML allows the user to select only one option from multiple options. In this tutorial, we will learn how to create a group of HTML radio buttons and get which one is selected using JavaScript.
Creating a Group of Radio Buttons in HTML
In HTML radio buttons are grouped by a unique name
attribute. If the radio input does not have the same name
attribute it will be independently selectable. In the example below only one of the following radio buttons can be selected because they all have the name
attribute of day
:
<label for="monday">Monday</label>
<input type="radio" name="day" id="monday">
<label for="tuesday">Tuesday</label>
<input type="radio" name="day" id="tuesday">
<label for="wednesday">Wednesday</label>
<input type="radio" name="day" id="wednesday">
How to Get the Selected Radio Button
Since we know a group of radio buttons is defined by a name
attribute we can get them using the JavaScript document.getElementsByName()
method, passing the name
attribute inside the ()
(parenthesis) of the method.
This will return an object of elements. All we have to do is iterate through the object using a for of loop and check which one is selected using the JavaScript .checked
method.
<label for="monday">Monday</label>
<input type="radio" name="day" id="monday" value="1">
<label for="tuesday">Tuesday</label>
<input type="radio" name="day" id="tuesday" value="2" checked="checked">
<label for="wednesday">Wednesday</label>
<input type="radio" name="day" id="wednesday" value="3">
var days = document.getElementsByName('day');
for (let i of days) {
if (i.checked) {
console.log(i.id);
}
}
tuesday
The above example gets the ID
of the radio button if it is checked. To get the value of a radio button use the value
JavaScript property:
var days = document.getElementsByName('day');
for (let i of days) {
if (i.checked) {
console.log(i.value);
}
}
Get the Selected Radio Button Without Iterating
It is possible to get the selected radio button without iterating by using the JavaScript document.querySelector()
method.
<label for="monday">Monday</label>
<input type="radio" name="day" id="monday" value="1">
<label for="tuesday">Tuesday</label>
<input type="radio" name="day" id="tuesday" value="2" checked="checked">
<label for="wednesday">Wednesday</label>
<input type="radio" name="day" id="wednesday" value="3">
var selected = document.querySelector('input[name="day"]:checked').id;
console.log(selected);
tuesday
The above example gets the ID
of the radio button that is checked. Alternatively, you could get its value
like this:
var selected = document.querySelector('input[name="day"]:checked').value;
console.log(selected);
2
Conclusion
You now know two different ways of getting the selected radio button using JavaScript.