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>
To obtain the value of the selected button using JavaScript, you might initially attempt this code:
var rates = document.getElementById('rates').value;
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;
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!