简体   繁体   English

如何在 <html:select> 页面何时加载?

[英]How do I display the selected values in an <html:select> when the page loads?

I have a JSP page which contains an HTML <select> populated with all countries loaded from a database. 我有一个JSP页面,其中包含HTML <select>填充了从数据库加载的所有国家。 Say for example, on "create user" all the country values are loaded in the select menu and I select 5 countries. 举例来说,在“创建用户”上,所有国家/地区值均已加载到选择菜单中,而我选择了5个国家/地区。 Those 5 values are loaded into database for that particular user. 这5个值将被加载到该特定用户的数据库中。

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. 现在,当我再次单击该用户ID的“修改用户”时,将出现一个选择菜单,所有国家/地区都将加载到该选择菜单中,但是应该突出显示/选择这5个国家/地区。

How do I accomplish this using javascript ? 如何使用javascript完成此操作?

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. 据我了解,不需要javascript。 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. 如果要使用AJAX动态更新列表,则需要将所选属性添加到需要突出显示的项目中。 You can easily do that with a javascript library. 您可以使用javascript库轻松完成此操作。

javascript may not be the best answer, although it is certainly doable that way. javascript可能不是最好的答案,尽管肯定可以这样做。

In the JSP page, I'm assuming you have a loop that populates the HTML <select> options. JSP页面中,我假设您有一个填充HTML <select>选项的循环。 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. 如果是这样,请在该国家的<option>添加一个selected="selected"属性/值对。

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. 如果您确实想在javascript执行此操作,则将应用相同的逻辑:遍历selectoption元素,并为适当的元素设置selected为true。

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. 或者,您可以让JSP生成适当的javascript行以仅设置所选的那些options ,从而在页面加载时保存遍历所有国家/地区的循环。

Have the javascript function invoked through the page load event so that the selections are made when the page is displayed. 通过page load事件调用javascript函数,以便在显示页面时进行选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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