How to get the selected radio button value in JavaScript?
Get the value of the selected radio button with querySelector and :checked, form.elements or FormData, and handle the case when nothing is selected yet.
Find the checked radio in the group by its name and read its value:
<form class="order">
<fieldset>
<legend>Size</legend>
<label><input type="radio" name="size" value="s"> Small</label>
<label><input type="radio" name="size" value="m"> Medium</label>
<label><input type="radio" name="size" value="l"> Large</label>
</fieldset>
</form>const size = document.querySelector(
'input[name="size"]:checked'
)?.value;
// 'm', or undefined when nothing is selectedquerySelector returns null when no radio in the group is checked. The optional chaining (?.) stops that from throwing and gives you undefined instead, so check for it before you use the value. If the user has to pick something, add required to the radios, or check one of them by default.
form.elements
If the radios are inside a form, the form already has them grouped by name:
const form = document.querySelector('.order');
form.elements.size.value; // 'm', or '' when nothing is selected
form.elements.size.value = 'l'; // checks the Large radioWhen several inputs share a name, form.elements.size is a RadioNodeList. Its value is the value of the checked radio, or an empty string when none is checked. Setting value checks the radio with that value. If no radio has it, nothing changes.
One trap: if the form has only one input with that name, form.elements.size is that input itself, not a list. Its value is then the input's value whether it's checked or not.
FormData
const data = new FormData(form);
data.get('size'); // 'm', or null when nothing is selectedThis is handy when you read the whole form on submit anyway. Object.fromEntries(new FormData(form)) gives you an object like { size: 'm' }, and a group with nothing selected is simply missing from it.
Listen to the whole group with one listener
The change event bubbles, so a single listener on the form or the fieldset covers every radio:
form.addEventListener('change', (event) => {
if (event.target.name === 'size') {
updatePrice(event.target.value);
}
});It fires only on the radio that became checked, not on the one that got unchecked, so event.target.value is always the new choice.
How radio groups work
- Radios with the same
nameform a group, and only one of them can be checked. Different names make separate groups. - Give every radio a
value. Without one, its value is the string'on', which doesn't tell you which option was picked. - A group is a single Tab stop, and the arrow keys move between the options. That's a good reason to style real radio inputs rather than rebuild them from divs.
- Clicking a checked radio doesn't uncheck it. If "no choice" should be possible, add an option like "No preference".
For checkboxes, which work differently, see how to check if a checkbox is checked.