Search code examples
jsplistboxstruts2strutsjsp-tags

default value in struts2 list box


we have list box.This will show the different states in US. I want state "LA" should be as preselected.But I dont know the position of "LA" in the list. It may vary.We are using the following script for this.

<select id="state" name="state" title="State" class="js_required prompt_text grid_2" tabindex="5">
                <option>State</option>
                <s:iterator value="@com.homeservices.action.utils.StateCode@values()">
                    <option value="<s:property/>"><s:property/></option>
                </s:iterator>
</select>

var @com.homeservices.action.utils.StateCode@values() gives a list of values:

AA
AE
AK
CA
CT
IL
LA
MA
MD

......etc.

Can some one please suggest how to make LA as a preselected state.


Solution

  • The Struts Approach

    <s:select id="state"
              name="state"
              title="State"
              headerKey=""
              headerValue="State"
              list="@action.StateCode@values()"
              cssClass="js_required prompt_text grid_2"
              value="@action.StateCode@LA"
              tabindex="5"/>
    

    The JSP Approach (JSTL/JSP-EL)

    <%@ page import="action.StateCode" %>
    <c:set var="states" value="<%=StateCode.values()%>"/>
    
    <select id="state" name="state" title="State"
            class="js_required prompt_text grid_2" tabindex="5">
        <option>State</option>
        <c:forEach items="${states}" var="state">
            <option value="${state}" ${state == 'LA' ? 'selected="selected"' : ''}>${state}</option>
        </c:forEach>
    </select>