How do you get the currently selected radio button using jQuery?
To get the currently selected radio button in a group using jQuery, query $('input[name="groupName"]:checked') and call .val() to retrieve its value. If no option in that group is checked, .val() returns undefined.
1. Getting the Selected Value and Element
Target the specific radio group by its name attribute so you do not accidentally read a checked radio button from another form or section on the page.
// Get the value of the selected radio button (returns undefined if none checked)
const selectedValue = $('input[name="billingPlan"]:checked').val();
console.log("Selected value:", selectedValue);
// Get the matched jQuery radio element and underlying DOM node
const $selectedRadio = $('input[name="billingPlan"]:checked');
const selectedDomEl = $selectedRadio.get(0);
if ($selectedRadio.length > 0) {
console.log("A radio button is selected:", selectedDomEl.id || selectedValue);
}
.val()behavior: Returns the stringvalueof the checked input, or"on"if the<input type="radio">lacks avalueattribute.- Checking
.length: Use$selectedRadio.length > 0to verify whether a selection exists before reading properties from the element.
2. Tracking Selection Changes Dynamically
Attach a change event listener to the named radio group so you always read the latest selection whenever the user switches options.
$('input[name="billingPlan"]').on("change", function () {
const currentValue = $(this).val();
const isChecked = $(this).is(":checked");
console.log("Changed value:", currentValue, "| Checked:", isChecked);
});
- Why
thisis reliable inside.on("change"):thispoints to the radio input that triggered the change, so$(this).val()gives the active selection directly. - Reading on form submit: Query
$('input[name="billingPlan"]:checked').val()inside yoursubmithandler right when the user submits. — ## 3. Common Traps to Avoid - Omitting thenameattribute: Using$('input[type="radio"]:checked').val()grabs the first checked radio button across the entire document, which breaks when multiple radio groups exist. - Forgetting
undefinedwhen nothing is checked: Provide a safe fallback when needed, such as$('input[name="billingPlan"]:checked').val() ?? "monthly". - Missingvalueattributes on radio inputs: Without avalueattribute, browsers default the value to"on", which rarely matches meaningful state or API payloads. — TL;DR: Use$('input[name="groupName"]:checked').val()to get the selected radio button’s value in jQuery, check.length > 0to see if any option is chosen, and listen to.on("change", ...)for live updates.
Are you reading the selected radio value on form submission, reacting live to .on("change"), or setting a radio button as checked via JavaScript?
You must log in or register to comment.
