如何解决Spring MVC根据数据库中的数据动态设置复选框
当尝试基于Spring MVC中从数据库返回的值设置要检查的复选框时,我遇到了一些问题。因此,基本上我有2组数组,一组包含ID标识的复选框数据的完整列表,另一组仅包含ID本身。我想做的是首先循环显示要显示的复选框数据的完整列表,然后循环播放仅包含ID的数组,如果ID匹配,则将复选框设置为选中状态。
我的控制器类:
// list to get full list of checkbox data to be displayed
List changeOfParticularsReasons = batchCardApplication.getBatchChangeOfParticularList(reasonReplacementId);
model.addAttribute("changeOfParticularsList",changeOfParticularsReasons);
// list to get the ID to be checked,it is just a string array with IDs
String[] changeParticularsDetailTOArray = new String[changeParticularsDetailTOList.size()];
for(int i = 0; i < changeParticularsDetailTOList.size(); i++){
ChangeParticularsDetailTO changeParticularsDetailTO = (ChangeParticularsDetailTO) changeParticularsDetailTOList.get(i);
changeParticularsDetailTOArray[i] = String.valueOf(changeParticularsDetailTO.getChangedParticularId());
}
model.addAttribute("selected",changeParticularsDetailTOArray);
我的JSP:
<c:if test="${!empty selected}">
<c:forEach var="change" items="${changeOfParticularsList}" varStatus="theIndex">
<tr>
<td align="left" width="5%">
<input type="checkbox" name="selected"
value="${change.replacementTypeID}" ${(newDisabled == true) ? 'disabled' : ''} />
<c:forEach var="selectedItem" items="${selected}">
<c:if test="${selectedItem == change.replacementTypeID}">
<input type="checkbox" name="selected" checked
value="${change.replacementTypeID}" ${(newDisabled == true) ? 'disabled' : ''} />
</c:if>
</c:forEach>
</td>
<td align="left" width="95%">
<c:out value="${change.replacementType}" />
</td>
</tr>
</c:forEach>
</c:if>
我得到的是什么
有什么办法解决此问题吗? ID的值仅为1到10。谢谢!
解决方法
实际上,您在选中时有条件地渲染了整个第二个复选框,而不是有条件地仅在已渲染的复选框中{strong>仅渲染了checked
属性。基本上与您对disabled
属性使用的方法相同。
调整此部分
<input type="checkbox" name="selected"
value="${change.replacementTypeID}" ${(newDisabled == true) ? 'disabled' : ''} />
<c:forEach var="selectedItem" items="${selected}">
<c:if test="${selectedItem == change.replacementTypeID}">
<input type="checkbox" name="selected" checked
value="${change.replacementTypeID}" ${(newDisabled == true) ? 'disabled' : ''} />
</c:if>
</c:forEach>
到
<input type="checkbox" name="selected"
value="${change.replacementTypeID}" ${(newDisabled == true) ? 'disabled' : ''}
${selected.contains(change.replacementTypeID) ? 'checked' : ''} />
并将selected
模型调整为List<String>
而不是String[]
,以便可以使用List#contains()
方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。