Reputation: 291
I have an HTML form like
<form name="radio-mc">
<input type="radio" name="mc" id="radio-1" value="1"> First
<input type="radio" name="mc" id="radio-2" value="2"> Second
<input type="radio" name="mc" id="radio-3" value="3"> Third
</form>
I can get the selected value in Chrome by form/input name with the following javascript
document.forms['radio-mc']['mc'].value
But in Firefox, the value is undefined.
I would normally think this was a specialty of Chrome but in the Firefox inspector I can see that parent object is an [object NodeList]
that has a value
property. It's simply not set to anything... seemingly ever.
I cannot use jQuery in this situation. Is there any way to get that one value in vanilla javascript in Firefox (without iterating over the radio buttons like I can in Chrome)?
Upvotes: 3
Views: 1845
Reputation: 147453
Prior to the introduction of the Selectors API, the only way to get the value of a radio button group was to iterate over the members:
function getRadioValue(group) {
for (var i=0, iLen=group.length; i<iLen; i++) {
if (group[i].checked) {
return group[i].value;
}
}
// No button selected - return '' or undefined?
return '';
}
console.log(getRadioValue(document.forms['radio-mc']['mc'])); // value
However, as cookie monster commented, you can use querySelectorAll for browsers that support it:
var checked = document.forms['radio-mc'].querySelector('input:checked');
console.log(checked? checked.value : '');
If you have more than one set of radio buttons in the form, or also have checkboxes, you'll need something like:
document.forms['radio-mc'].querySelector('[name=mc]:checked')
otherwise you'll just get the first checked radio or checkbox.
Also, since you don't have a default selected button, you need to handle the case where no button is selected.
Upvotes: 5