0

I am trying to populate a dropdown . I have a hashmap, from which i am getting key and value. I have a bean from which i am getting a string value. Now i want to populate the dropdown like this :

If the bean value is equal to hashmap key, then i have to make the key and value as "selected" in the dropdown otherwise, the string "plz select a value" must become the default drop down selected element and other key value pairs must come after it. If the bean value is equal to hashmap key, then they must not be repeated again.

This is what i have till far :

<%
String defaultText = "Please select a value";
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) i.next();
// getKey Method of HashMap access a key of map
String keyValue = (String) mapEntry.getKey();
//getValue method returns corresponding key's value
String value = (String) mapEntry.getValue();

%>

<option  selected="selected" value="none">
<%
if( beanNo!=null && beanNo.equals(keyValue))
{
%>
<%= beanNo %> , <%= value %>
<%
}
else
{
%>
<%= defaultText %>
<%
}
%>
</option>
<option  value="">
<%= value %> , <%= keyValue %>
</option>
<%
}
%>

However, this is not giving me the desired result. If the bean value is equal to hashMap keyValue, then, the same value is coming up twice and the defaultText is not coming at all .

Where am i going wrong ? Kindly help ?

The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
  • Please [avoid](http://stackoverflow.com/a/3180202/1037210) this hateful Scriptlet. Move Java code to Java beans ( along with Servlets). Follow JSTL along with some frameworks of your choice and requirement (with ORM like Hibernate or JPA). – Lion Nov 28 '12 at 14:34
  • Cant use that, the project is an out dated one and the need the code in those formats . – The Dark Knight Nov 28 '12 at 14:46

1 Answers1

2

This should work better :

<%
    String defaultText = "Please select a value";
%>
<option value="none"><%= defaultText %></option>
<%
    while (iterator.hasNext())
    {
        Map.Entry mapEntry = (Map.Entry) i.next();
        // getKey Method of HashMap access a key of map
        String keyValue = (String) mapEntry.getKey();
        //getValue method returns corresponding key's value
        String value = (String) mapEntry.getValue();
%>
<option <%= (beanNo!=null && beanNo.equals(keyValue)) ? "selected=\"selected\"" : "" %> value="<%= value %>">
<%= keyValue %>
</option>
<%
    }
%>

Note : it has not been tested nor verified for syntax, maybe there are some minor errors.

Alexandre Lavoie
  • 8,711
  • 3
  • 31
  • 72