简体   繁体   中英

How to populate jsp drop down?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM