Question

I have created a radio button using Struts tags however i am attempting to get the selected value of the radio button however i am unable to get the value. Under is what i have done thus far.

Jsp

<s:radio name="gender" id= "gender" list="#{'1':'Male','2':'Female'}" onChange="genderChange()"/>

Javascript function

function genderChange(){
 var gendervalue;
 genderValue = document.getElementById("gender").value;
 alert(gendervalue);

}

Console Error

TypeError: document.getElementById(...) is null
Était-ce utile?

La solution

The solution was for me to pass the element value into the java script function under is my updated code

Jsp

<s:radio name="gender" id= "gender" list="#{'1':'Male','2':'Female'}" onChange="genderChange(this.value)"/>

Javascript function

function genderChange(value){
 var gendervalue;
 genderValue = value;
 alert(gendervalue);

}

Autres conseils

If you see your page in HTML you can see that two radio buttons will be create, with 2 different ids: gender1 and gender2. You can access to your value with:

var foo = document.getElementById("gender1").checked;

In this case, if the first is checked (foo==true), the other will be not checked.

A more scalable solution is using:

document.getElementsByName("gender")[index].checked

where index is a number that indentify all radio buttons with the name "gender". You can make a FOR to cycle the array and find at which index checked is true.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top