为什么“已检查”属性不适用于我的Thymeleaf的复选框?

时间:2018-08-02 23:28:46

标签: spring checkbox thymeleaf checked

遇到以下问题时,我正在使用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
}

谢谢。

2 个答案:

答案 0 :(得分:1)

我也一直在为此苦苦挣扎。如Xaltotun所述,如果使用th:field,它将覆盖checked和value选项,因为它正试图从field/form获取value和checked选项。

如果将其更改为th:name,它应该可以按照您想要的方式工作... 但是,此forum似乎可以与th:feild一起使用。

答案 1 :(得分:0)

据我了解,您的帖子中有2个问题:

  1. 虚拟示例不正确。

    th:checked =“ $ {1 == 1?'checked':''}”

实际上,该值必须为true或false而不是“选中”。如果您尝试

<pre>newarray: {{ newarray | json }}</pre>
<pre>tbarArray: {{ tbarArray | json }}</pre>

它将起作用。

  1. 如果您设置th:field =“ * {ids}”,则该复选框应尝试从字段 item.ids 获取值,并且不会使用“ th:checked”或“ th:value”属性。该商品是否具有字段 id
相关问题