Getting Selected Radio Button Value
A common task when working with forms is retrieving the value of the selected radio button. In this context, a JavaScript program encountered an issue where the radio button value was returning undefined.
The provided code for the findSelection function iterates over all radio buttons in a form, checking which one is checked and returning its value. However, the code had a problem in its initial setup where it mistakenly assigned the form name to both the test and sizes variables.
A simplified and effective solution to this problem is to use the following code:
document.querySelector('input[name="genderS"]:checked').value;
This code uses the document.querySelector method to select the checked radio button by its name attribute ("genderS"). The :checked selector ensures that only the checked radio button is selected. The value property retrieves the value of the selected radio button.
This solution is compatible with all major browsers and requires no additional libraries like jQuery
The above is the detailed content of How to Get the Value of a Selected Radio Button in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!