An onchange handler on a group of radio buttons (<input type="radio" name="...">) fires only for the newly selected (checked) radio button—and not for the previously selected radio button that became unchecked—because HTML radio buttons are mutually exclusive by name, and the browser’s form-control state-change model treats selection of the newly checked radio button as the primary state transition while automatically unchecking the prior option as a side effect of mutual exclusion. Furthermore, in standard HTML/DOM behavior, change on radio buttons fires when the checked state changes via user interaction (and in some older/specific cases after blur/commit, though in modern browsers clicking or arrow-keying a radio button fires change on the newly checked input), never dispatching a separate change event on the input that was deselected.
1. Mutual Exclusion and Event Dispatch Behavior on Radio Groups
When radio buttons share the same name attribute, selecting option B unchecks option A implicitly—the browser dispatches change on option B (radio.checked === true), not on option A:
// Inspect which radio input receives `change` inside a mutually exclusive group
function bindRadioGroupChange(groupSelector, onSelectionChange) {
if (typeof groupSelector !== "string" || groupSelector.trim().length === 0) {
throw new TypeError("Expected groupSelector to be a non-empty CSS selector string.");
}
if (typeof onSelectionChange !== "function") {
throw new TypeError("Expected onSelectionChange to be a function.");
}
if (typeof document === "undefined") {
throw new Error("DOM document is unavailable.");
}
const container = document.querySelector(groupSelector);
if (!container) {
throw new Error(`No container found for selector "${groupSelector}".`);
}
let previousValue = null;
const initiallyChecked = container.querySelector('input[type="radio"]:checked');
if (initiallyChecked) {
previousValue = initiallyChecked.value;
}
const handleChange = (event) => {
try {
const target = event.target;
if (!(target instanceof HTMLInputElement) || target.type !== "radio") {
return;
}
// Only the newly checked radio triggers `change`; track previous selection manually
const nextValue = target.checked ? target.value : null;
onSelectionChange({
previousValue,
currentValue: nextValue,
inputElement: target
});
previousValue = nextValue;
} catch (error) {
console.error(`Radio group change handler failed: ${error.message}`);
}
};
container.addEventListener("change", handleChange);
return () => container.removeEventListener("change", handleChange);
}
// Example usage:
// const cleanup = bindRadioGroupChange("#plan-group", ({ previousValue, currentValue }) => {
// console.log(`Changed from ${previousValue ?? "none"} to ${currentValue}`);
// });
- Track
previousValuein application/closure state: Since the deselected radio input does not firechange, store the prior value when needed to compare old vs. new choices. - Use event delegation on the parent container/fieldset: Avoids looping over individual radio inputs and handles dynamically added radios cleanly.
2. Programmatic .checked = true Does Not Fire change
Setting radio.checked = true (or radio.checked = false) in JavaScript updates the DOM property without firing input or change events automatically—so if your UI logic depends on a change event, you must invoke your state-update function directly or dispatch a change event explicitly:
// Programmatically select a radio by value and notify listeners when requested
function setRadioValueProgrammatically(name, targetValue, { dispatchChange = false } = {}) {
if (typeof name !== "string" || name.trim().length === 0) {
throw new TypeError("Expected radio group name to be a non-empty string.");
}
if (typeof targetValue !== "string") {
throw new TypeError("Expected targetValue to be a string.");
}
if (typeof document === "undefined") {
throw new Error("DOM document is unavailable.");
}
const escapedName = typeof CSS !== "undefined" && typeof CSS.escape === "function"
? CSS.escape(name)
: name.replace(/[^a-zA-Z0-9_-]/g, "\\$&");
const radios = Array.from(document.querySelectorAll(`input[type="radio"][name="${escapedName}"]`));
const match = radios.find((radio) => radio.value === targetValue);
if (!match) {
throw new Error(`No radio input with name="${name}" and value="${targetValue}" found.`);
}
match.checked = true;
if (dispatchChange) {
match.dispatchEvent(new Event("change", { bubbles: true }));
}
return match;
}
// Example usage:
// setRadioValueProgrammatically("billingCycle", "annual", { dispatchChange: true });
- Avoid infinite loops when dispatching manually: Ensure your handler does not call
setRadioValueProgrammatically(..., { dispatchChange: true })back onto the same radio group. - Check
radio.valuebefore trusting selection: Ifvalueattributes are omitted in HTML,radio.valuedefaults to"on", which can make multiple options indistinguishable.
3. Grouping and Accessibility Gotchas with Radio Buttons
When radio buttons behave unexpectedly or miss expected events, check group naming, keyboard navigation, and label association:
- Missing or mismatched
nameattributes: Radio inputs without the samenameact as independent toggles rather than a single exclusive group, allowing multiple options to stay checked. - Keyboard arrow selection: Pressing
ArrowUp/ArrowDown/ArrowLeft/ArrowRighton a focused radio group moves selection to the next/previous radio and triggerschangeon that newly checked radio. - Wrap radios in
<fieldset>+<legend>and pair each input with a<label>: Improves accessibility and makes clicking labels reliably select the corresponding radio button.
