Site icon

How to get selected radio button value in Javascript

selected radio button value in Javascript

To get the selected radio button value using JavaScript, you can follow these steps:

1. HTML Setup:
First, create an HTML form with radio buttons. Each radio button should have a unique value associated with it.

“`html
<form id=”myForm”>
<input type=”radio” name=”option” value=”option1″> Option 1
<input type=”radio” name=”option” value=”option2″> Option 2
<input type=”radio” name=”option” value=”option3″> Option 3
<!– Add more radio buttons if needed –>
</form>
“`

2. JavaScript Code:
Next, you can use JavaScript to get the value of the selected radio button when a form submission or a specific event occurs.

“`html
<script>
function getSelectedRadioValue() {
// Get the form element
const form = document.getElementById(“myForm”);

// Get all radio buttons with the same name attribute
const radioButtons = form.elements[“option”];

// Loop through the radio buttons to find the selected one
for (let i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
// Return the value of the selected radio button
return radioButtons[i].value;
}
}

// If no radio button is selected, return null or handle the case accordingly
return null;
}

// Example usage:
function onFormSubmit() {
const selectedValue = getSelectedRadioValue();
if (selectedValue !== null) {
console.log(“Selected value:”, selectedValue);
} else {
console.log(“Please select an option.”);
}
}
</script>
“`

In the above example, the `getSelectedRadioValue` function retrieves the value of the selected radio button from the form. You can use this function to get the selected value and perform any further actions based on the user’s selection. The example usage shows how to call the function when the form is submitted, but you can trigger it based on your application’s requirements (e.g., on button click, on page load, etc.).

Exit mobile version