How to Get the Selected Value of a Radio Button in JavaScript

When working with radio buttons in a form, you may want to retrieve the value of the selected option. This can be achieved using JavaScript by accessing the group of radio buttons with the same name attribute and checking which one is selected. Following are the steps with example:


<form>
<label>
<input type="radio" name="color" value="Red"> Red
</label>
<label>
<input type="radio" name="color" value="Blue"> Blue
</label>
<label>
<input type="radio" name="color" value="Green"> Green
</label>
<button type="button" onclick="getSelectedValue()">Submit the colour</button>
</form>

<script>
function getSelectedValue() {
// Select all radio buttons with the name 'color'
const radios = document.getElementsByName('color');
let selectedValue = '';

// Iterate through the radio buttons
for (const radio of radios) {
if (radio.checked) {
selectedValue = radio.value;
break; // Exit loop once a checked radio is found
}
}

if (selectedValue) {
alert(`Selected value: ${selectedValue}`);
} else {
alert('No value selected!');
}
}
</script>

  • document.getElementsByName('color'): It gets all radio buttons with the name attribute color.
  • radio.checked: Checks if a radio button is get selected.
  • Iterating through the radio buttons: Loops through all radio buttons and gets the value of the checked one.
  • Handle case where no button is selected: Ensures you provide feedback if no radio button is selected.

Output:

  • If “Red” is selected, it alerts: Selected value: Red.
  • If no radio button is selected, it alerts: No value selected!.

Leave a Comment