Set HTML dropdown selected option using JSTL

sarah picture sarah · Apr 21, 2010 · Viewed 125.1k times · Source

In the same context i have another query

<select multiple="multiple" name="prodSKUs">
            <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
          <option value="${productSubCategoryList}"${productSubCategoryList == productSubCategoryName ? 'selected' : ''}>${productSubCategoryList}</option>
         </c:forEach>
        </select>

and the corresponding setting in request is like

for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    request.setAttribute("productSubCategoryName",productSubCategoryName);

}

here i have multiple select drop down ,even though i get the return value from for as two ,in the UI only one data is getting higlighted not the second one,What is wrong in the code ?

Answer

Maurice Perry picture Maurice Perry · Apr 21, 2010

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>