Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set HTML dropdown selected option using JSTL

Tags:

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 ?

like image 442
sarah Avatar asked Apr 21 '10 10:04

sarah


1 Answers

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> 
like image 75
Maurice Perry Avatar answered Oct 21 '22 03:10

Maurice Perry