HTML dropdown set by default selected from database in JSP / servlet

I have an HTML form for storing and editing a dataset. I have a dropdown in the form. My problem when opening the edit page is how to set the default value for the dropdown as soon as I got from the database. I am currently using JSTL tags to add the "selected" attribute in an if condition. But if I have 100 values ​​in the drop-down list, meeting the if condition 100 times does not look like 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, whats the best way to encode it. I am using JSP / Servlets with an SQL database.

+4
source share
1 answer

Since you have an SQL database, I think you can make a list of 100 types of operations. If you create an ArrayList<String> containing types, and set it as a request attribute named operationTypes , you can use c:forEach to repeat 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> 
+3
source

Source: https://habr.com/ru/post/1435393/


All Articles