Checking Value of Radio Button Group via JavaScript?
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;
}
update
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 are using a javascript library like jQuery, it's very easy:
alert($('input[name=gender]:checked').val());
This code will select the checked
input with gender
name, and gets it's value
. Simple isn't it?
Live demo