How do you get the selected value of a radio button group in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you get the selected value of a radio button group in JavaScript?

message-square
0

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 :checked match: 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 in groupName via CSS.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 formElement without constructing selector strings.
  • Safe fallback: Returns fallback (null by default) when no radio in the group is checked or formElement is invalid.

3. Common Traps to Avoid

Reading the selected value of a radio button group in JavaScript often runs into a few pitfalls:

  • Calling .value directly on querySelectorAll('input[name="..."]'): NodeList does not have a .value property of its own—you must find the :checked HTMLInputElement first.
  • Forgetting the null case when no radio is checked: If no radio button in the group has a default checked attribute or prior selection, querySelector(...:checked) returns null.
  • Reusing the same name across two separate forms on the same page: Unscoped document.querySelector() picks the first matching :checked input in document order—pass { root: formEl } or use FormData(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.