Domanda

I populate the options of select element from types variable. Lets say option1 and option2. I get option1 from selectedType variable. Problem is when I click on dropdown I see three options to select {opion1, option2, option1}. Selected option is added to already populated options. Please suggest me where I am going wrong ?

<select name="types">
<c:forEach items="${types}" var="type">
<option>${type}</option>
</c:forEach>
<option selected="selected">${selectedType}</option>
</select>
È stato utile?

Soluzione

You are adding duplicated options, it is necessary to compare inside the forEach if it is the selected one and then mark it as selected

Something like this:

<select name="types">
<c:forEach items="${types}" var="type">
    <c:when test="${type == selectedType}">
        <option selected="selected">${selectedType}</option>
    </c:when>
    <c:otherwise>
        <option>${type}</option>
    </c:otherwise>
</c:forEach>
</select>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top