Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected value for JSP drop down using JSTL

I have SortedMap in Servlet to populate drop down values in JSP and I have the following code

    SortedMap<String, String> dept = findDepartment();
    request.setAttribute("dept ", dept);

and in JSP

       <select name="department">
          <c:forEach var="item" items="${dept}">
            <option value="${item.key}">${item.value}</option>
          </c:forEach>
        </select>

I am using one JSP page for insert and update. When I am editing the page how can I set selected value to drop down where selected value will come from database.

like image 384
Jacob Avatar asked Mar 27 '13 11:03

Jacob


2 Answers

In HTML, the selected option is represented by the presence of the selected attribute on the <option> element like so:

<option ... selected>...</option> 

Or if you're HTML/XHTML strict:

<option ... selected="selected">...</option> 

Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:

request.setAttribute("selectedDept", selectedDept); 

then this should do:

<select name="department">     <c:forEach var="item" items="${dept}">         <option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>     </c:forEach> </select> 

See also:

  • How can I retain HTML form field values in JSP after submitting form to Servlet?
like image 123
BalusC Avatar answered Sep 17 '22 20:09

BalusC


i tried the last answer from Sandeep Kumar, and i found way more simple :

<option value="1" <c:if test="${item.key == 1}"> selected </c:if>>
like image 27
Muchtarpr Avatar answered Sep 20 '22 20:09

Muchtarpr