0

I have 2 arraylists in JSP that are passed from controller servlet: allOptionsList and alreadySelectedOptionsList.

I am trying to generate HTML form with <select> dropdown and I want to show all items from allOptionsList as an <option> within <select> but, I want for items that are in alreadySelectedOptionsList to be shown as <option selected="selected">.

This is what I already have:

<select name="options" size="20">
     <c:forEach items="${allOptionsList}" var="optionAll">
        <option>${optionAll.optionName}</option>
     </c:forEach>
</select>

Basicly I want for option is to be selected if it is already in the alreadySelectedOptionsList list. How can I achieve this?

aki
  • 1,731
  • 2
  • 19
  • 24

2 Answers2

0

Use c:if

<select name="options" size="20">
     <c:forEach items="${allOptionsList}" var="optionAll">
        <c:if test="${optionAll.selected == 'true'}">
            <option>${optionAll.optionName}</option>
        </c:if>
     </c:forEach>
</select>
jmj
  • 237,923
  • 42
  • 401
  • 438
  • but I have to compare it to alreadySelectedOptionsList to see if it is already selected. If it is in alreadySelectedOptionsList than it should be printed as " – aki Jan 13 '12 at 07:29
0

If you're targeting a Servlet 3.0 container which supports EL 2.2 feature of invoking methods with arguments (e.g. Tomcat 7, Glassfish 3, etc), then you could use List#contains() method for this.

<select name="options" size="20">
     <c:forEach items="${allOptionsList}" var="optionAll">
        <option ${alreadySelectedOptionsList.contains(optionAll.optionName) ? 'selected' : ''}>${optionAll.optionName}</option>
     </c:forEach>
</select>

But if you're targeting an older container which doesn't support invoking methods in EL, then you need to create a custom EL function which does the job. You can find a concrete example in this answer: How can i do a multiselect in jsp/jstl with selected value?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I have done indeed something like what you are suggesting, only in java because I am using 2.5 container. I have created third object which contains boolen isSelected field. I compared the objects from two lists and for objects that are in both lists, I set isSelected to true. All this new objects are placed in a list, which is then returned to view. It is actually the same solution that you are sugesting. – aki Jan 14 '12 at 11:51