首页 > 解决方案 > 使用两个字符串集合检查 Thymeleaf 复选框

问题描述

我有两个字符串集合。

一种是生成所有复选框。

另一种是选择要检查的元素。

例如,我有两个字符串集合 ["A", "B", "C", "D"] ["A", "C"]

我想做 4 个复选框 A、B、C、D 并想检查 A 和 C

我尝试如下。

    <span th:each="interestName : ${allInterest}">
        <span th:each="interest : ${userInfo.interestName}">
            <input type="checkbox"
               name="eachUserInterest"
               th:value="${interestName.name}"
                th:checked="${interestName.name.equals(interest)}"/>
            <label th:text="${interestName.name}"></label>
        </span>
    </span>

但是,上面的代码会重复生成一个复选框,其次数与选中的次数一样多。 执行结果

请帮帮我。

标签: springspring-bootcheckboxthymeleaf

解决方案


您应该只遍历allInterest数组,并使用contains来确定是否选中了复选框。例如这样的事情:

<th:block th:each="interest: ${allInterest}">
  <input type="checkbox"
         name="eachUserInterest"
         th:value="${interest}"
         th:checked="${userInfo.interestName.contains(interest)}" />
  <label th:text="${interest}"></label>
</th:block>

推荐阅读