【问题标题】:Get value of dropdown in JSP and load other contents depending on the value selected获取 JSP 中下拉列表的值并根据选择的值加载其他内容
【发布时间】:2015-08-20 17:15:22
【问题描述】:

我有一个 JSP 页面,其中有一个下拉项目列表。我正在使用列表类型的请求属性填充此下拉列表并遍历该下拉列表。

<select class="form-control" id="groupname" name="groupname">
    <c:forEach items="${visibility}" var="groupListItem">
        <option value="${groupListItem.groupName}">${groupListItem.groupName}</option>
    </c:forEach>
</select>

每当我从下拉列表中选择一个项目时,我都需要在同一页面上显示一个复选框列表。复选框的标签和选中/未选中值也是列表属性的一部分,groupListItem

list 属性是一个自定义 bean,它有一个带有复选框名称和值的映射,用于决定是选中还是未选中。

如何在选择下拉值时获取复选框的值?

我的列表属性如下所示。

List<GroupVisibilityBean> groupList = driverDAO.getGroupVisibility();
model.addAttribute("visibility", createGroup());

private List<GroupVisibilityBean> createGroup() {
    List<GroupVisibilityBean> groupList = new ArrayList<GroupVisibilityBean>();

    GroupVisibilityBean bean1 = new GroupVisibilityBean();
    bean1.setGroupName("GARDA");
    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("Personal Details", "Y");
    map1.put("Driver Details", "N");

    GroupVisibilityBean bean2 = new GroupVisibilityBean();
    bean2.setGroupName("COURT");
    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("Personal Details", "Y");
    map2.put("Driver Details", "N");

    groupList.add(bean1);
    groupList.add(bean2);

    return groupList;
}

有人可以帮我吗?

【问题讨论】:

    标签: javascript java html jsp


    【解决方案1】:
    1. 您可能需要将创建的map1map2 分别添加到您的bean1bean2。现在,它们被赋值了,但你没有像这样的调用

      bean1.setCheckboxMap(map1);
      

      这可能需要帮助bean1 访问map1 等。

    2. 当您在 bean 中有值时,您需要将它们放入 HTML 页面中。最简单的方法是(例如,在您的 foreach 中的 &lt;option&gt; 下方)

      <script>
        ${groupListItem} = {}; // create object of that name
        <c:forEach items="${groupListItem.checkboxMap}" var="mapItem">
            ${groupListItem}["${mapItem.key}"] = "${mapItem.value}"; // set val
        </c:forEach>
      </script>
      

      你可以将 bean 的值存储在一个 JS 数组中,而不是使用键作为 JS 对象的键,如下所示

      <script>
        ${groupListItem} = {}; // create object of that name
        ${groupListItem}.keys = [];
        ${groupListItem}.values = [];
        <c:forEach items="${groupListItem.checkboxMap}" var="mapItem">
            ${groupListItem}.keys.push("${mapItem.key}"); // append key
            ${groupListItem}.values.push("${mapItem.value}"); // append value
        </c:forEach>
      </script>
      

      另见how-to-iterate-an-arraylist-inside-a-hashmap-using-jstl。如果您想多花点功夫,请将其编码为 JSON,如 reading-a-jsp-variable-from-javascript

    3. 如果值在 HTML 中,您需要更改复选框或在更改下拉列表时通过 Javascript 即时创建它们。如需检测下拉事件,请参阅dropdown-using-javascript-onchange

    【讨论】:

    • 嗨..谢谢你的详细信息。我错过了向 bean 添加地图属性。但首先在 jsp 中,我将显示一个包含组名列表的下拉列表。然后根据选定的下拉项,我将显示复选框。我仍然不确定如何从组列表中获取所选项目并显示同一组的复选框映射。
    猜你喜欢
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多