最近在做struts的時候用到了,html:radio來表示性別。但是在使用的過程中遇到了不能動態選中的問題。後來在網上查找後基本的解決方案是:
Given a set of <html:radio> controls like this:
<html:radio property="expectedVia" value="UPS"/>UPS
<html:radio property="expectedVia" value="FEDX"/>Federal Express
<html:radio property="expectedVia" value="AIRB"/>AirBorne
And that the expectedVia property on the form bean was already set to "UPS", then the HTML radio elements would be rendered like this:
<input type="radio" name="expectedVia" value="UPS" checked="checked">UPS
<input type="radio" name="expectedVia" value="FEDX">Federal Express
<input type="radio" name="expectedVia" value="AIRB" >AirBorne
If you need to create a dynamic set of radio buttons, or want to localize the values, you can create in an Action a collection of LabelValueBeans with the appropriate labels and values for each button. Here's an example:
ArrayList shippers = new ArrayList();
shippers.add(new LabelValueBean("UPS", "UPS"));
shippers.add(new LabelValueBean("Federal Express", "FEDX"));
shippers.add(new LabelValueBean("AirBorne", "AIRB"));
request.setAttribute ("SHIPPERS",shippers);
Then, on the page, you can iterate through the collection
<logic:iterate id="row" name="SHIPPERS" type="org.apache.commons.scaffold.util.LabelValueBean">
<html:radio property="expectedVia" value="<%=row.getValue()%>"/>
<bean:write name="row" property="label"/>
</logic:iterate>
So long as one of the values matches the "expectedVia" property on our ActionForm, the radio tag will still automatically select the appropriate button.
上面的解釋可以大概概括如下:
1.如果是固定的值,比如性別:男,女。你只需把value的屬性設置爲各自的值。然後當頁面顯示的時候會自動把從frombean中對應的數據給選中。
2.如果你是動態生成的radio,就用logic:iterate就可以了。
但是我按上述的第一中方法編寫如下jsp代碼:
<html:radio property="sex" value="F" name="member">女</html:radio>
action過來的form bean中也設置了sex的值。但是radio就是不選中。
後來沒辦法,只能用java script來實現了。
function setChecked(value){
if(value=="M")
{
document.forms[0].sex[0].checked=true;
}
else
{
document.forms[0].sex[1].checked=true;
}
</script>其中memberInfo是該頁面中引用form bean的<bean:define的Id。
然後在jsp最後加上下面的代碼:
setChecked(<%=memberInfo.getSex()%>)
</script>
這樣設置後運行正常!!