If you want vanilla JavaScript, don't want to clutter your markup by adding IDs on each radio button, and only care about modern browsers, the following functional approach is a little more tasteful to me than a for loop:
<form id="myForm">
<label>Who will be left?
<label><input type="radio" name="output" value="knight" />Kurgan</label>
<label><input type="radio" name="output" value="highlander" checked />Connor</label>
</label>
</form>
<script>
function getSelectedRadioValue (formElement, radioName) {
return ([].slice.call(formElement[radioName]).filter(function (radio) {
return radio.checked;
}).pop() || {}).value;
}
var formEl = document.getElementById('myForm');
alert(
getSelectedRadioValue(formEl, 'output') // 'highlander'
)
</script>
If neither is checked, it will return undefined
(though you could change the line above to return something else, e.g., to get false
returned, you could change the relevant line above to: }).pop() || {value:false}).value;
).
There is also the forward-looking polyfill approach since the RadioNodeList interface should make it easy to just use a value
property on the list of form child radio elements (found in the above code as formElement[radioName]
), but that has its own problems: How to polyfill RadioNodeList?