我有一个 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;
}
有人可以帮我吗?
最佳答案
您可能需要添加创建的
这样的调用map1
和map2
给您bean1
和bean2
, 分别。现在,它们已被赋值,但您没有像bean1.setCheckboxMap(map1);
这可能需要帮助
bean1
访问map1
等等当 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 所示。 .
如果值采用 HTML 格式,则您需要更改复选框或在更改下拉列表时通过 Javascript 即时创建它们。要检测下拉事件,请参阅 dropdown-using-javascript-onchange .
关于javascript - 在JSP中获取下拉列表的值并根据所选值加载其他内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32124386/