4
votes

I have a HTML form for storing and editing a set of data. I have a dropdown box in the form too. My problem while opening the edit page is how can I set the default value of the dropdown as the one I just got from database. Currently I use JSTL tags to add the attribute "selected" by an if condition. But if I have 100 values in the dropdown, executing the if condition 100 times doesnt look a good option. Here is what I have right now.

<select name="outageType" id="outageType" class="span3">
<option
<c:if test='${operation.type == "Type1"}'>selected="selected"</c:if>
value="Type1">Type1</option>
<option
<c:if test='${operation.type == "Type2"}'>selected="selected"</c:if>
value="Type2">Type2</option>
<option
<c:if test='${operation.type == "Type3"}'>selected="selected"</c:if>
value="Type3">Type3</option>
</select>

So if I have 100 values, what is the best way to code it. I am using JSP/Servlets with SQL database.

1

1 Answers

3
votes

Since you have a SQL database, I guess you can come up with list of the 100 operation types. If you create a ArrayList<String> containing the types and set it as a request attribute named operationTypes, you can use c:forEach to iterate through the list:

<select name="outageType" id="outageType" class="span3">
  <c:forEach items="${operationTypes}" var="operationType">
    <option ${operation.type == operationType
             ? 'selected="selected"' 
             : ''
             } value="<c:out value="${operationType}"/>">
      <c:out value="${operationType}"/>
    </option>
  </c:forEach>
</select>