29

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.

Majid
  • 12,271
  • 14
  • 71
  • 107
Jacob
  • 13,463
  • 58
  • 188
  • 302

8 Answers8

49

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:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • BalusC `request.setAttribute("selectedDept", selectedDept);` I presume that here `selectedDept` is my database value for department right? – Jacob Mar 27 '13 at 11:15
  • Then it that case I should have two request `request.setAttribute("dept ", dept);` and `request.setAttribute("selectedDept", selectedDept);`? – Jacob Mar 27 '13 at 11:19
  • Uh yes. Did you face a problem while trying that? – BalusC Mar 27 '13 at 11:21
6

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>>
Muchtarpr
  • 71
  • 1
  • 2
3

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 );
Uri Lukach
  • 1,055
  • 1
  • 13
  • 27
  • Thanks Uri, I will try this. – Jacob Mar 27 '13 at 11:30
  • 1
    This approach fails if JS is disabled. – BalusC Mar 27 '13 at 11:33
  • @Uri Here how can I specify servlet class? Because for my datatable I am using a servlet, I would specify another servlet controller for select component. – Jacob Apr 02 '13 at 08:46
  • @Polppan do you mean how to refer to another Controller from you JSP page? if so, you can use return ModelAndView with another controller name from your main controller or add the Java behaviour you need to your main controller. I think this question should have a different post... – Uri Lukach Apr 03 '13 at 06:07
3

I think above examples are correct. but you dont' really need to set

request.setAttribute("selectedDept", selectedDept);

you can reuse that info from JSTL, just do something like this..

<!DOCTYPE html>
<html lang="en">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<head>
    <script src="../js/jquery-1.8.1.min.js"></script>
</head>
<body>
    <c:set var="authors" value="aaa,bbb,ccc,ddd,eee,fff,ggg" scope="application" />
    <c:out value="Before : ${param.Author}"/>
    <form action="TestSelect.action">
        <label>Author
            <select id="Author" name="Author">
                <c:forEach items="${fn:split(authors, ',')}" var="author">
                    <option value="${author}" ${author == param.Author ? 'selected' : ''}>${author}</option>
                </c:forEach>
            </select>
        </label>
        <button type="submit" value="submit" name="Submit"></button>
        <Br>
        <c:out value="After :   ${param.Author}"/>
    </form>
</body>
</html>
Sendi_t
  • 572
  • 3
  • 13
2

I tried the accepted answer, it did not work.

However the simple way to do it is below:-

<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>

Enjoy!!

2

You can try one even more simple:

<option value="1" ${item.quantity == 1 ? "selected" : ""}>1</option>
zeirna
  • 21
  • 1
1

Maybe I don't completely understand the accepted answer so it didn't work for me.

What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected

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

because none of the options are selected, thus item = null

<%
    if(item == null){
        item = "selectedDept"; //known value from your database
    }
%>

This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me

sicnarfmis
  • 36
  • 6
0

Below is Example of simple dropdown using jstl tag

 <form:select path="cityFrom">  
    <form:option value="Ghaziabad" label="Ghaziabad"/>  
    <form:option value="Modinagar" label="Modinagar"/>  
    <form:option value="Meerut" label="Meerut"/>  
    <form:option value="Amristar" label="Amristar"/>  
 </form:select>
Yoshita Mahajan
  • 167
  • 1
  • 6