3

In my project. I want to populate the drop down list on a jsp from a database.

<select id="names" name="names"> <c:forEach items="${names}" var="names">
        <option><c:out value="${names}"/></option>
    </c:forEach>
</select>

The ${names} is a list of names from the database. I want to select an option dynamically in the drop down list. Suppose there are three names in the database Rohan, Dean, Justin. If Dean is logged, i want select the option Dean as selected.

I try a code like this but this does not work.

<option value="${names}" ${names == names ? 'selected' : ''}>${names}</option>
4
  • You could post the code showing what have you tried. This is better than just asking how to do the things. Commented Sep 5, 2012 at 5:01
  • Comparing strings should be done with equals() not with == Commented Sep 5, 2012 at 5:02
  • And names == names is useless... Commented Sep 5, 2012 at 5:03
  • First, you should change the name of that local names var to name, just for easier maintenance. Second, you're comparing names with names (and you should use equals to compare String variables), like 1 == 1, you should compare the name variable with a request or session parameter that handles the actual userName or another variable you want/need. Commented Sep 5, 2012 at 5:10

1 Answer 1

2

Try like this assuming that loggedInUser variable holds the String value of the currently logged in user.

<select id="names" name="names">
<c:forEach items="${names}" var="names">

    <c:when test="${loggedInUser eq names}">    
        <option value ="<c:out value="${names}"/>" selected="selected">${names}</option>
    </c:when>
    <c:otherwise>
        <option><c:out value="${names}"/></option> 
    </c:otherwise>  
</c:forEach>

Sign up to request clarification or add additional context in comments.

2 Comments

You should point that loggedInUser is a String request parameter as well and it is available at that moment.
Based in the OP posted code, it looks like he/she still has problems in that area.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.