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

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

DDD
Release: 2024-12-09 04:37:13
Original
206 people have browsed it

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

Utilizing JavaScript to Determine the Selected Radio Button Value

To obtain the selected value from a group of radio buttons, the 'value' attribute associated with the checked radio button must be accessed. In earlier versions of Internet Explorer, this required a specific approach. However, for IE9 and subsequent versions, as well as all other browsers, a simplified method is available:

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

This code snippet utilizes the querySelector() method to select the input element that has the 'name' attribute set to 'rate' and the 'checked' attribute set to 'true', representing the selected radio button. It then returns the 'value' attribute of the selected radio button.

In the HTML provided:

<div>
Copy after login

executing the following code will yield the selected value:

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

For instance, if the radio button with the value 'Multi Rate' is checked, 'rate_value' will be set to 'Multi Rate'. By utilizing this approach, the selected value can be efficiently obtained, regardless of the specific radio button selected.

The above is the detailed content of How to Get the Value of a Selected Radio Button Using 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