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

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

Mary-Kate Olsen
Release: 2024-12-15 12:21:10
Original
329 people have browsed it

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

Getting Selected Radio Button Value

A common task when working with forms is retrieving the value of the selected radio button. In this context, a JavaScript program encountered an issue where the radio button value was returning undefined.

The provided code for the findSelection function iterates over all radio buttons in a form, checking which one is checked and returning its value. However, the code had a problem in its initial setup where it mistakenly assigned the form name to both the test and sizes variables.

A simplified and effective solution to this problem is to use the following code:

document.querySelector('input[name="genderS"]:checked').value;
Copy after login

This code uses the document.querySelector method to select the checked radio button by its name attribute ("genderS"). The :checked selector ensures that only the checked radio button is selected. The value property retrieves the value of the selected radio button.

This solution is compatible with all major browsers and requires no additional libraries like jQuery

The above is the detailed content of How to 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