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

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

DDD
Release: 2024-12-13 01:13:09
Original
553 people have browsed it

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

Determining the Selected Radio Button Value

To retrieve the value of the selected radio button within a group, you may encounter difficulties using conventional methods. This article provides a solution to this common issue.

Consider the following HTML structure for a set of radio buttons:

<div>
Copy after login

To obtain the value of the selected button using JavaScript, you might initially attempt this code:

var rates = document.getElementById('rates').value;
Copy after login

However, this approach retrieves the ID of the containing div element instead of the selected radio button value. To address this issue, utilize the following code:

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

This code uses the querySelector method to select the first matching radio button element within the rates div, ensuring that you obtain the value of the checked button specifically.

The above is the detailed content of How Can I 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template