Home > Web Front-end > JS Tutorial > How Do I Efficiently Get the Value of a Selected Radio Button in JavaScript?

How Do I Efficiently Get the Value of a Selected Radio Button in JavaScript?

Patricia Arquette
Release: 2024-12-14 22:13:11
Original
657 people have browsed it

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;
        }
    }
}
Copy after login

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;
Copy after login

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:

  • Browser Compatibility: This method works seamlessly across various web browsers.
  • Simplicity: It's a concise and straightforward approach that eliminates the need for complex loops or iterators.
  • Dynamic: It dynamically selects the checked radio button, irrespective of its position in the DOM.

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>
Copy after login

JavaScript:

function submitForm() {
    var gender = document.querySelector('input[name="genderS"]:checked').value;
    alert(gender);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template