Explain Codes LogoExplain Codes Logo

How to get the value of a selected radio button

javascript
radio-button
browser-compatibility
jquery
Nikita BarsukovbyNikita Barsukov·Oct 1, 2024
TLDR

To fetch the value of the selected radio button, simply run:

let selectedValue = document.querySelector('input[name="groupName"]:checked')?.value;

Ensure to replace groupName with your radio button group's name. The use of the ? operator shields against null values when no button is selected, effectively preventing errors. This one-liner retrieves and presents the value of the chosen radio button swiftly.

What about browser compatibility?

This method works like a charm with IE9+ and all modern browsers. Be careful not to call the .value property on a div, it's like asking a fish to climb a tree; swimming is to fish, as .value is to radio inputs.

jQuery squad, where you at?

If you're part of the jQuery fan club, this elegant line has your back:

let selectedValue = $("input[name='groupName']:checked").val();

This does the same job but in jQuery style.

Check please!

To confirm if a radio button is selected or not, the .checked property rides to the rescue:

let isSelected = document.getElementById('radioId').checked; // because trust issues 😉

This boolean expression helps ensure an option is selected before you proceed to the next step in your application logic.

Iterating the Node way

By looping through all radio buttons sharing the same name with document.getElementsByName('groupName') and checking .checked on each, you can work out which is selected:

let rates = document.getElementsByName('groupName'); let rate_value; for (let i = 0; i < rates.length; i++) { // because friendship is important 😄 if (rates[i].checked) { rate_value = rates[i].value; break; // because your code also needs a break 😉 } }

This method ensures that no radio button gets left out!

The element of forms

You can retrieve the value by leveraging form elements' properties:

let form = document.querySelector('form'); let selectedValue = form.elements["groupName"].value;

If you're navigating through a jungle of form controls, cling to the elements collection.

Advanced radio broadcasting

For the advanced out there working with complex forms, meet the RadioNodeList, your new BFF for browsers like Firefox 33+:

let selectedValue = document.forms['myForm']['groupName'].value; // RadioNodeList in action!

Here, document.forms['myForm'] refers to your form by name or ID, and ['groupName'] is the name of your radio button group.

Beware of the undefined

In cases where no radio button is selected, the value could return undefined. To prevent your app from throwing a fit, sprinkle in some validation checks or set a default selection.