How to Get the Value of a Selected Radio Button in HTML and JavaScript
Radio buttons allow users to select a single option from a group of related choices. Retrieving the value of the selected radio button is a common task in web development.
Problem:
You are unable to retrieve the selected value from a group of radio buttons using your current JavaScript code.
Solution:
To get the value of the selected radio button, you can use the following improved code:
const selectedRadio = document.querySelector('input[name="rate"]:checked'); if (selectedRadio) { const rateValue = selectedRadio.value; document.getElementById('results').innerHTML = rateValue; }
Explanation:
The querySelector() method searches for the first element in the DOM that matches the specified selector. In this case, it targets the radio button with the name attribute "rate" and the checked attribute.
Once the selected radio button is obtained, its value property is retrieved and stored in the rateValue variable. Finally, the innerHTML property of the results element is set to the rateValue, effectively displaying the selected radio button's value.
The above is the detailed content of How Do I Get the Value of a Selected Radio Button in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!