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
Mary-Kate OlsenOriginal
2024-12-15 12:21:10333browse

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;

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!

Statement:
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