How to display selected values ​​in <html: select> on page load?

I have a page JSP

that contains HTML

<select>

, populated with all countries loaded from the database. Let's say for example "create user" all country values ​​are loaded into the select menu and I select 5 countries. These 5 values ​​are loaded into the database for that particular user.

Now when I click on "change user" for that user again, a selection menu will appear and all countries will be loaded into the selection menu, but these 5 countries must be highlighted / selected.

How do I do this using javascript

?

0


source to share


2 answers


I'm not sure if I understood the question correctly, but here is a list of several options:

<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, javascript is not required. If you want to use AJAX to dynamically update the list, you need to add the selected attribute to the elements you want to highlight. You can easily do this with a javascript library.

+2


source


javascript

may not be the best answer, although it certainly is possible.

On the page, JSP

I assume you have a loop that fills in the parameters HTML

<select>

. In this loop, place a test to see if the current value was selected for the user. If so, add a couple of attributes / values selected="selected"

in <option>

for that country.

If you really want to do it in javascript

, the same logic applies: loop through the elements option

for select

and set to selected

true for the corresponding elements.



Alternatively, you can create JSP

matching lines javascript

to set only the ones options

that have been selected, keeping the cycle across all countries on page load.

Calling a javascript function via an event page load

so that the selection is made when the page is rendered.

0


source







All Articles