Home >Web Front-end >JS Tutorial >How to Avoid 'Undefined' When Retrieving Selected Radio Button Values?
Obtaining the selected value from a group of radio buttons can be crucial in web development. However, your current code is encountering the issue of returning "undefined." This issue stems from the approach of obtaining the selected value via the "rates" div.
To effectively retrieve the selected value, utilize the following code snippet:
document.querySelector('input[name="rate"]:checked').value;
This code employs the document.querySelector() method to locate the checked radio button within the group. It accomplishes this by specifying the name attribute and the :checked pseudo-class, ensuring precision in the selection. Once the checked radio button is identified, the value property is accessed to retrieve its associated value.
This approach is supported in IE9 and above, as well as all other modern browsers. It provides a straightforward and reliable way to obtain the selected value from a group of radio buttons, eliminating the "undefined" issue you encountered.
The above is the detailed content of How to Avoid 'Undefined' When Retrieving Selected Radio Button Values?. For more information, please follow other related articles on the PHP Chinese website!