Home >Web Front-end >JS Tutorial >How Do I Efficiently Get the Value of a Selected Radio Button in JavaScript?
Accessing Radio Button Value in JavaScript
When working with radio button inputs in JavaScript, it's essential to retrieve the value of the selected option. However, encountering issues with such implementations can be frustrating. Let's investigate a common problem and its solution.
Problem
Consider the following code snippet:
function findSelection(field) { var test = 'document.theForm.' + field; var sizes = test; for (i=0; i < sizes.length; i++) { if (sizes[i].checked==true) { return sizes[i].value; } } }
Despite its intended purpose, this code consistently returns 'undefined' when attempting to access the selected radio button value.
Solution
To resolve this issue, we can leverage a modern approach using the querySelector() method:
document.querySelector('input[name="genderS"]:checked').value;
This line of code retrieves the value of the selected radio button by utilizing the :checked selector within the querySelector() method.
Advantages
This solution offers several benefits:
Implementation
HTML:
<form action="#n" name="theForm"> <label for="gender">Gender: </label> <input type="radio" name="genderS" value="1" checked> Male <input type="radio" name="genderS" value="0" > Female<br><br> <a href="javascript: submitForm()">Search</a> </form>
JavaScript:
function submitForm() { var gender = document.querySelector('input[name="genderS"]:checked').value; alert(gender); }
Note: You don't need to include a jQuery path in this implementation.
The above is the detailed content of How Do I Efficiently Get the Value of a Selected Radio Button in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!