views:

2487

answers:

2

I have a JSP page which contains an HTML <select> populated with all countries loaded from a database. Say for example, on "create user" all the country values are loaded in the select menu and I select 5 countries. Those 5 values are loaded into database for that particular user.

Now when I click on "modify user" for that userid again there will be a select menu and all the countries will be loaded in the select menu but those 5 countries should be highlighted/selected.

How do I accomplish this using javascript?

+2  A: 

I am not sure if I understand the question correctly, but here is a multiple selection list:

<select multiple="multiple">
  <option value ="UK">UK</option>
  <option value ="France" selected="selected">France</option>
  <option value ="Germany">Germany</option>
  <option value ="Italy" selected="selected">Italy</option>
</select>

As I understand it, no javascript is required. If you want to use AJAX to update the list dynamically, then you need to add the selected attribute to the items that need to be highlighted. You can easily do that with a javascript library.

kgiannakakis
A: 

javascript may not be the best answer, although it is certainly doable that way.

In the JSP page, I'm assuming you have a loop that populates the HTML <select> options. In that loop, place a test to see if the current value was selected for the user. If so, add a selected="selected" attribute/value pair to the <option> for that country.

If you really want to do this in javascript, the same logic applies: loop through the option elements for the select, and set selected to true for the appropriate elements.

As an alternative, you can have your JSP generate the appropriate javascript lines to set only those options that are selected, saving a loop through all countries on page load.

Have the javascript function invoked through the page load event so that the selections are made when the page is displayed.

Ken Gentle