I created a radio button in struts however i saw the radio button accepts a list so i provided a list {true:'Yes',false:'No'}
. This creates a radio button pair with Yes and No labels however i would like to use javascript to get the radio button thats checked.
When the radio buttons are created they are give Id's with 'name'true and 'name'false. I am confused as to how i will use javascript to get the checked radio button and its value. Under is my code:
Struts Radio Button
<s:radio name="over18" id= "over18Stat" list="#{true:'Yes',false:'No'}"
onclick="Over18Changed(this.value)"/>
Javascript
I have tried this however it does not work
var ofage = document.getElementByName('over18').value ;
The getElementsByTagName is plural as it returns a (possibly empty) NodeList of elements that match the given name.
To get the selected button, loop over the NodeList (I've turned it into a function):
function getCheckedButton(name) {
var buttons = document.getElementsByName(name);
for (var i=0; i<buttons.length; i++) {
if (buttons[i].checked) {
return buttons[i];
}
}
If you just want the button's value:
return buttons[i].value
You could also use querySelector:
function getCheckedValue(name) {
var button = document.querySelector('input[name=' + name + ']:checked');
return button && button.value;
}
However, querySelector isn't supported by all browsers in use and complex selectors aren't supported by all those that support querySelector.