javascript - 在JSP中获取下拉列表的值并根据所选值加载其他内容

标签 javascript java html jsp

我有一个 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 的一部分。

列表属性是一个自定义 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;
}

有人可以帮我吗?

最佳答案

  1. 您可能需要添加创建的 map1map2给您bean1bean2 , 分别。现在,它们已被赋值,但您没有像

    这样的调用
    bean1.setCheckboxMap(map1);
    

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

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

    <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 .

关于javascript - 在JSP中获取下拉列表的值并根据所选值加载其他内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32124386/

相关文章:

javascript - 从文本框中获取整数值,如何检查它是 NaN 还是 null 等?

java - 泛化类和继承问题

html - Flexbox - 如何左对齐最后一个 flex 元素?

html - 将文本与复选框对齐

javascript - 绑定(bind)、应用和调用方法之间的区别?

javascript - 在不点击输入的情况下填写输入时显示新的 div

javascript - 有没有办法从 ajax 预检请求中获取调试信息?

java - 从 Facelets 1.x 迁移到 Facelets 2.0

java - Spring Servlet 3.0 异步 Controller - 什么线程处理响应?

python - 从单个网页中抓取多个表格