Sometimes, we want to get the selected radio button value using JavaScript.
In this article, we’ll look at how to get the selected radio button value using JavaScript.
How to get the selected radio button value using JavaScript?
To get the selected radio button value using JavaScript, we use the :checked
pseudoselector.
For instance, we write
<p>Gender</p>
<input type="radio" id="gender0" name="gender" value="Male" />Male<br />
<input type="radio" id="gender1" name="gender" value="Female" />Female<br />
to add radio buttons.
Then we write
const gender = document.querySelector('input[name = "gender"]:checked').value;
to select the selected radio button with name attribute gender
with querySelector
.
And we get its value with value
.
Conclusion
To get the selected radio button value using JavaScript, we use the :checked
pseudoselector.