Radio buttons are a popular way to make selections on web forms and applications. If you're working with JavaScript and want to retrieve the value of a selected radio button, you're in the right place. In this guide, we'll walk you through the steps to get the selected radio button value using plain JavaScript.
To begin, let's set up a simple example with an HTML form that includes radio buttons:
Option 1
Option 2
Option 3
<button type="button">Get Value</button>
In the above code snippet, we have three radio buttons with values "option1," "option2," and "option3" respectively. Additionally, we included a button with an `onclick` event that will trigger a function to get the selected value.
Now, let's dive into the JavaScript code that will allow us to retrieve the selected radio button value:
function getSelectedValue() {
const radioButtons = document.getElementsByName('choice');
let selectedValue;
for (const radioButton of radioButtons) {
if (radioButton.checked) {
selectedValue = radioButton.value;
break;
}
}
if (selectedValue) {
alert(`Selected Value: ${selectedValue}`);
} else {
alert('Please select an option');
}
}
In the `getSelectedValue` function, we first use `document.getElementsByName('choice')` to retrieve all radio buttons with the name "choice." We then loop through each radio button and check if it is checked. If a radio button is checked, we store its value in the `selectedValue` variable and break out of the loop.
After the loop, we check if a value was selected. If a value is found, we display an alert with the selected value. Otherwise, we notify the user to select an option.
To test this functionality, simply copy the HTML and JavaScript code snippets into an HTML file and open it in a web browser. You can select a radio button and click the "Get Value" button to see the selected value displayed in an alert dialog.
By following these steps, you now know how to get the selected radio button value using JavaScript in your web projects. This straightforward approach can be easily integrated into various applications where radio buttons are used for user input. Feel free to experiment further and enhance this functionality based on your specific requirements.