How to get the selected radio button value using js
Solution 1:
HTML
<p>Gender</p>
<input type="radio" id="gender0" name="gender" value="Male">Male<br>
<input type="radio" id="gender1" name="gender" value="Female">Female<br>
JS
var gender = document.querySelector('input[name = "gender"]:checked').value;
document.writeln("You entered " + gender + " for your gender<br>");
Solution 2:
If you are using jQuery, following code will work for you.
$('input[name=radioName]:checked').val();
Solution 3:
Radio buttons come in groups which have the same name and different ids, one of them will have the checked property set to true, so loop over them until you find it.
function getCheckedRadio(radio_group) {
for (var i = 0; i < radio_group.length; i++) {
var button = radio_group[i];
if (button.checked) {
return button;
}
}
return undefined;
}
var checkedButton = getCheckedRadio(document.forms.frmId.elements.groupName);
if (checkedButton) {
alert("The value is " + checkedButton.value);
}