【问题标题】:Why "checked" attribute doesn't apply to my Thymeleaf's checkboxes?为什么“选中”属性不适用于我的 Thymeleaf 的复选框?
【发布时间】: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


    【解决方案1】:

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

    如果您将其更改为th:name,它应该可以按照您的意愿工作... 但是这个forum 似乎有助于使用th:feild

    【讨论】:

      【解决方案2】:

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

      1. 虚拟示例不正确。

        th:checked="${1 == 1 ? 'checked' : ''}"

      事实上,该值必须为真或假而不是“检查”。如果您尝试使用

      th:checked="${1 == 1}"/>
      

      它会起作用的。

      1. 如果您设置 th:field="*{ids}" 那么复选框应该尝试从字段 item.ids 中获取值,并且不会使用“th:checked”或“th:value”属性。项目是否有字段 ids

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2019-05-06
        • 2016-11-15
        • 2021-11-16
        • 2018-09-15
        相关资源
        最近更新 更多