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;
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>
executing the following code will yield the selected value:
var rate_value = document.querySelector('input[name="rate"]:checked').value;
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!