最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jsp - Struts 2 get radio button value using javascript - Stack Overflow

programmeradmin1浏览0评论

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

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
Share Improve this question asked Mar 30, 2014 at 15:40 devdardevdar 5,65428 gold badges104 silver badges156 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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);

}

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.

发布评论

评论列表(0)

  1. 暂无评论