Developer Desk Developer Desk - 1 month ago 6
Java Question

How to compare two arraylist and set option selected in jsp?

I have two tables:

Table 1

geoCountry
with columns

country_name | country_code


Table 2
user_countries
with columns

country_name | username


I want to set users country pre-selected (i.e fetching from db)

Here is code that I have tried

<select multiple="multiple" class="country" style="width: 200px">
<%
sql6 = "SELECT DISTINCT countryname FROM user_countries WHERE username = ?";
ps6 = connection.prepareStatement(sql6);
ps6.setString(1, user);
rs6 = ps6.executeQuery();

while (rs6.next()) {
usercountries.add(rs6.getString(1));
}

for (int i = 0; i < geoCountry.size(); i++) {
for (int j = 0; j < usercountries.size(); j++) {
if (usercountries.get(j).equals(geoCountry.get(i))) {
%>
<option value="<%=geoCountry.get(i)%>" selected="selected"><%=geoCountry.get(i)%></option>
<% } else {%>
<option value="<%=geoCountry.get(i)%>"><%=geoCountry.get(i)%></option>
<% }
}
} %>
</select>


it is showing duplicated values in select box .. why?

Answer

Remove second cycle with " usercountries", thms. like:

  for (int i = 0; i < geoCountry.size(); i++) {
         if (usercountries.contains(geoCountry.get(i)) {
             %>
            <option value="<%=geoCountry.get(i)%>" selected="selected"><%=geoCountry.get(i)%></option>
             <% } else {%>
             <option value="<%=geoCountry.get(i)%>"><%=geoCountry.get(i)%></option>
          <% }
       } %>
Comments