To get the selected value of a radio button group in JavaScript, query the checked radio input sharing that name using document.querySelector('input[type="radio"][name="..."]:checked') (scoped to a container or form when needed) and read .value, returning null (or a fallback value) when no option in the group is checked. Always escape or validate the group name and avoid mutating DOM elements or collection results.
1. Reading the Checked Radio Value with document.querySelector() and :checked
Target the specific name and :checked pseudo-class within an optional container (root), verify the matched element is an HTMLInputElement, and return its .value or null when nothing is selected:
// Get the selected value of a radio button group by name, or null if none is checked
function getSelectedRadioValue(groupName, { root = document, fallback = null } = {}) {
if (typeof groupName !== "string" || groupName.trim() === "") {
return fallback;
}
const scope =
root && typeof root.querySelector === "function" ? root : document;
const escapedName =
typeof CSS !== "undefined" && typeof CSS.escape === "function"
? CSS.escape(groupName)
: groupName.replace(/["\\]/g, "\\$&");
const checkedRadio = scope.querySelector(
`input[type="radio"][name="${escapedName}"]:checked`
);
if (!(checkedRadio instanceof HTMLInputElement)) {
return fallback;
}
return checkedRadio.value;
}
// Example usage:
// const plan = getSelectedRadioValue("billingPlan", { root: document.getElementById("signup-form") });
// console.log("Selected billing plan:", plan);
- Direct
:checkedmatch: Returns the currently checked radio button immediately without looping manually over every input in the group. - Scoping and escaping: Scopes lookups to a form or container (
root) and escapes special characters ingroupNameviaCSS.escape().
2. Reading Selected Radio Values from FormData
When reading values from an <form> element, new FormData(formElement).get(groupName) provides a clean alternative that returns the selected radio input’s value string or null if none is checked:
// Read the selected radio value from a form using FormData
function getSelectedRadioFromForm(formElement, groupName, fallback = null) {
if (!(formElement instanceof HTMLFormElement) || typeof groupName !== "string" || groupName.trim() === "") {
return fallback;
}
const formData = new FormData(formElement);
const value = formData.get(groupName);
return typeof value === "string" ? value : fallback;
}
// Example usage:
// const formEl = document.getElementById("preferences-form");
// console.log("Theme:", getSelectedRadioFromForm(formEl, "theme", "system"));
- Form-aware lookup: Reads directly from the submitted/current state of
formElementwithout constructing selector strings. - Safe fallback: Returns
fallback(nullby default) when no radio in the group is checked orformElementis invalid.
3. Common Traps to Avoid
Reading the selected value of a radio button group in JavaScript often runs into a few pitfalls:
- Calling
.valuedirectly onquerySelectorAll('input[name="..."]'):NodeListdoes not have a.valueproperty of its own—you must find the:checkedHTMLInputElementfirst. - Forgetting the
nullcase when no radio is checked: If no radio button in the group has a defaultcheckedattribute or prior selection,querySelector(...:checked)returnsnull. - Reusing the same
nameacross two separate forms on the same page: Unscopeddocument.querySelector()picks the first matching:checkedinput in document order—pass{ root: formEl }or useFormData(formEl)to isolate a specific form.
TL;DR: Query scope.querySelector('input[type="radio"][name="..."]:checked') (or new FormData(formEl).get(groupName)) and read .value, guarding against null when nothing is selected.
