Search code examples
htmljspstruts2radio-buttonstruts-tags

How to preselect a radio button inside of a Struts iterator based on the iterator value?


I have the following lines of code inside of a Struts2 <s:iterator> tag.

<s:radio name="indicatorFlag"  list = "seqNoMap" value="indicatorFlag" /></div> 
<div><s:property  value = "indicatorFlag"/></div>

The seqNoMap is a defined on my action page as follows.

seqNoMap = new HashMap<String, String>();
seqNoMap.put("Y", " Yes ");
seqNoMap.put("N", " No ");

The radio buttons show up on my page and passes the selection info back to the indicatorFlag field on the action page, but the value="indicatorFlag" in the <s:radio> tag does not preselect the radio button even though it does print out a Y or an N in the <s:property> tag on the second line. The indicatorFlag changes values as the iterator goes through the list (it is a field of the objects in the list being iterated). I have found several places which answer this question and I think I am applying the answers they give, but obviously I am missing something. Any help would be appreciated.

Here is the relevant code for the RefQuestionAction action page.

private HashMap<String, String> seqNoMap;  
private List<RefQuestionInfo> questionInfoList;
private String indicatorFlag;       // Char (1) flag

public RefQuestionAction(){
    seqNoMap = new HashMap<String, String>();
    seqNoMap.put("Y", " Yes ");
    seqNoMap.put("N", " No ");
}

Here is the code which defines the object RefQuestionInfo (The indicatorFlag is the only field involved in this question).

public class RefQuestionInfo extends BaseInfo implements Serializable {
    private int questionId;             
    private int seqNo;                  
    private String indicatorFlag;       
    private Date activeDate;            
    private Date inactiveDate;          
    private String question;            

Here is the Struts2 code inside of the <s:iterator> tag. I have stripped out most of the page code to focus on what my problem is.

<s:iterator value = "questionInfoList" var = "questionInfo">
    <s:radio name="indicatorFlag"  list = "seqNoMap" value="indicatorFlag" /> 
    <div><s:property  value = "indicatorFlag"/></div>
 </s:iterator> 

The output looks like this.

JSP page output

I want the Yes or No radio value to be preselected based on the Y or N which is on the line after the radio buttons.


Solution

  • Your all radio buttons have the same name, that means that you can have only one of them selected. Assign different names for them using iterator status.

    <s:iterator value="questionInfoList" var="questionInfo" status="stat">
      <s:radio name="indicatorFlag%{#stat.index}" list="seqNoMap" value="indicatorFlag" /> 
      <div><s:property value="indicatorFlag" /></div>
    </s:iterator>
    

    Note that you have variable with the same name indicatorFlag inside action and inside your RefQuestionInfo in the above code the one inside RefQuestionInfo will be used.