Search code examples
javascriptjspstruts-1scriptletstruts-tags

How to get Unique ID for a group of dropDowns generated by a loop?


Please Help me here to solve below problem.

Code:

<%for(int ind=0;ind<15;ind++){%>

 <tr>
   <struts-el:select name="OpEnh01pagSincomModelMaintanenceFormBean" property="mdlCode" styleId="mdlDrpDown_+'<%=ind %>'" onchange="modelCodeChanged(this.id)">
     <struts-el:options collection="listmodelCodes" property="modelCode" labelProperty="modelCodeDesc" />
   </struts-el:select> 
 </tr>

<%}%>

1) I want 15 dropdowns in 15 rows. I want dropDown's index to identify which dropDown is modified in JavaScript.

2) I want to get a unique id so that I can access it using dom in JavaScript called by onChangeEvent.

I have a form bean Name properties mdlDrpDown1, mdlDrpDown2 and so on..

I tried this format: styleId="mdlDrpDown_+'<%=ind %>'" but couldn't get it as styleId, property attribute are not runTimeExpr.


Solution

  • You are using dynamic property names mdlCode<%=ind %> for select, if getter and setter are not found in the formbean then No getter method Exception will be raised, to avoid this we can index based properties (which can holds multiple values based on index, index value will order of the elements appear in the page) instead of single properties (which can holds only one value).

    Try the below code:

    FormBean:

    //create getter and setter for `mdlCode` using String[], so it can hold dynamic values.
    
    String[] mdlCode;
    
    public String[] getMdlCode() {
       return mdlCode;
    }
    public void setMdlCode(String[] mdlCode) {
       this.mdlCode=mdlCode;
    }
    

    JSP:

    <%for(int ind=0;ind<15;ind++) {
        String id = "mdlDrpDown_"+ind;
    %>
    
    <tr>
        <!-- change property from `property="mdlCode<%=ind %>"` to property='mdlCode' -->
        <struts-el:select name="OpEnh01pagSincomModelMaintanenceFormBean" property="mdlCode" styleId="<%=id %>" onchange="modelCodeChanged(this.id)">
            <struts-el:options collection="listmodelCodes" property="modelCode" labelProperty="modelCodeDesc" />
        </struts-el:select> 
    </tr>
    
    <%}%>