在对象的javascript下拉列表中显示一个值

Display a value in a javascript dropdown list from an object

本文关键字:一个 显示 对象 javascript 下拉列表      更新时间:2023-09-26

我有一个javascript下拉列表,它是根据对象的"name"字段填充的。是否可以将整个对象放在下拉列表中,只显示名称?我之所以这么问,是因为我想根据用户选择的内容更改另一个下拉列表的值,并且该信息在第一个对象中已经可用(在我去掉名称之前)。

所以现在我有这个(Java控制器):

 List<String> hostsList = new ArrayList<String>();
 for (Client client : adminService.getClients()){
     hostsList.add(client.getName());
 }
 result.put("hostsList", hostsList);

然后在javascript方面:

<form:form id="iForm" method="post"
action="${pageContext.request.contextPath}/host"
commandName="hostsForm">
<td valign="top">Hosts:</td>
<td valign="top"><form:select path="uSetHostName">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${hostsList}" />
</form:select>
</td>

那么,我如何将整个对象放入下拉列表中并只显示其名称呢?

谢谢,

据我所知,您要求将Java对象转换为JavaScript对象,以便稍后在JavaScript中使用该对象来驱动下拉值。

有几种方法可以做到这一点。第一种方法是将每个Java Client对象表示为JavaScript对象,然后用JavaScript填充这两个下拉列表。这可能是使用某种JSON库(如Gson或Jackson)最简单的方法。下面是一个使用JQuery和Gson的示例:

<script lang="text/javascript">
    var clients = <%= new Gson().toJson(clients) %>;
    // Fill the first dropdown.
    $("#myDropdown").empty();
    $.each(clients, function() {
        $("<option/>").attr("value", this.id).text(this.name).appendTo("#myDropdown");
    });
    $("#myDropdown").on("change", function(event) {
        var selectedClientId = $("#myDropdown").val();
        var client = $.grep(clients, function(client) {
            return client.id = selectedClientId;
        });
        $("#myOtherDropdown").val(client.someOtherValue);
    });
</script>
...
<select id="myDropdown" name="..."></select>
...
<select id="myOtherDropdown" name="..."></select>

第二种方法是准确地执行您现在正在执行的操作,然后将填充另一个下拉列表所需的最小数量的Client对象放入JavaScript代码中。看起来像这样:

<script lang="text/javascript">
    var clientIdToOtherValueMap = {
        <%
        for (Client client : clients) {
            %>
            '<%= client.id %>': '<%= client.otherDropdownId %>',
            <%
        }
        %>
        '': ''
    };
    // Fill the first dropdown.
    $("#myDropdown").on("change", function(event) {
        $("myOtherDropdown").val(clientIdToOtherValueMap[$("#myDropdown").val()]);
    });
</script>
...
<select id="myDropdown" name="..."></select>
...
<select id="myOtherDropdown" name="..."></select>

希望这能帮助你开始!