Selected value for JSP drop down using JSTL
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>>
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?
If you don't mind using jQuery you can use the code bellow:
<script>
$(document).ready(function(){
$("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
});
</script>
<select id="department" name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
In the your Servlet add the following:
request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );