【发布时间】:2018-08-02 23:28:45
【问题描述】:
我在使用 Spring 和 Thymeleaf 时遇到以下问题:我需要一个 Form 对象,它有一个项目列表 (Item) 作为属性;我正在使用 html 表单来打印项目的名称,并为每个项目生成一个复选框(任何复选框的值都是相应项目的 id)。
表单工作正常,向控制器发送与选中复选框相对应的项目 ID 列表。
但是,现在,我正在尝试在出现条件时检查某个复选框(如果 itemIds 是一个列表,包含当前项目的 id)。为此,我正在使用:
th:checked="${#lists.contains(itemIds, item.id)}"/>
但它不起作用(复选框都未选中)。 我还尝试了“虚拟测试”:
th:checked="${1 == 1 ? 'checked' : ''}"/>
但是,再次,所有复选框都未选中;正如您在呈现的 HTML 示例中所见,“checked”属性被忽略:
<input type="checkbox" value="12" class="chkCheckBox" id="ids1" name="ids">
我做错了什么?我在这里错过了什么?
form.html
<form th:action="@{${uriBase}+'/new/' + ${date}}"
method="POST" th:object="${form}">
<div class="table-responsive">
<table class="table">
<thead class=" text-primary">
<tr>
<th>Name</th>
<th><input type="checkbox" th:id="checkAll"/>Check</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${items}">
<td th:text="${item.name}"></td>
<td>
<input type="checkbox" th:field="*{ids}"
th:value="${item.id}" th:class="chkCheckBox"
th:checked="${#lists.contains(itemIds, item.id)}"/>
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary pull-right">Submit</button>
<div class="clearfix"></div>
</div>
</form>
表单类
public class Form implements Serializable {
private List<Long> ids;
//getter and setter
}
提前谢谢你。
【问题讨论】:
标签: spring checkbox thymeleaf checked