This may seem silly and downright stupid but I can't seem to figure out how to check the value of a radio button group in my HTML form via JavaScript. I have the following code:
<input type="radio" id="genderm" name="gender" value="male" /> <label for="genderm">Male</label> <input type="radio" id="genderf" name="gender" value="female" /> <label for="genderf">Female</label>
How do I retrieve the value of gender
via JavaScript?
To get the value of selected radio button, a user-defined function can be created that gets all the radio buttons with the name attribute and finds the radio button selected using the checked property. The checked property returns True if the radio button is selected and False otherwise.
Radio buttons don't participate in constraint validation; they have no real value to be constrained.
Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).
document.querySelector('input[name="gender"]:checked').value
In pure Javascript:
var genders = document.getElementsByName("gender"); var selectedGender; for(var i = 0; i < genders.length; i++) { if(genders[i].checked) selectedGender = genders[i].value; }
In pure Javascript without loop, using newer (and potentially not-yet-supported) RadioNodeList
:
var form_elements = document.getElementById('my_form').elements; var selectedGender = form_elements['gender'].value;
The only catch is that RadioNodeList
is only returned by the HTMLFormElement.elements
or HTMLFieldSetElement.elements
property, so you have to have some identifier for the form or fieldset that the radio inputs are wrapped in to grab it first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With