html:radio 使用心得

 最近在做struts的時候用到了,html:radio來表示性別。但是在使用的過程中遇到了不能動態選中的問題。後來在網上查找後基本的解決方案是:

 

Each radio button element requires an assigned value that distinguishes it from the other radio buttons. When creating a static array of radio buttons, you need to indicate which one of these, if any, is checked. This does not need to be done when the radio buttons are being populated from dynamic data. The control can compare itself to the form bean's property and then check itself when appropriate.

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 value="M" property="sex" name="member"></html:radio>
<html:radio property="sex" value="F" name="member"></html:radio>

 

action過來的form bean中也設置了sex的值。但是radio就是不選中。

後來沒辦法,只能用java script來實現了。

 

<script type="text/javascript">
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最後加上下面的代碼:

 

<script type="text/javascript">
            setChecked(
<%=memberInfo.getSex()%>)
</script>

 

這樣設置後運行正常!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章