Thymeleaf单选按钮th:现场检查确认

时间:2019-06-01 12:13:39

标签: spring spring-boot spring-mvc thymeleaf

我正在尝试验证使用th:each创建的单选按钮的输入。 在输入中使用th:field在html中输出checked =“ checked”,这使一个单选按钮被选中,这是我所不希望的。如果我输入name =“ field”,则不会发生,但是不会进行字段验证,因为我不会使用th:field。

<form th:action="@{/dosomething}" th:object="${Object}" method="post">                                  
<div th:each="op : *{options}"> 
<input type="radio" th:field="*{options}" th:value="${op.id}"     th:id="${opStat.index}"/>                         
<label th:for="${opStat.index}" th:text="${op.optiontext}">Option   Text</label>
<button type="submit">Next</button>                 
</form>

<form action="/dosomething" method="post">                                  
<div>   
<input type="radio" value="1" id="0" name="options" checked="checked"/>                         
<label for="0">A</label>
</div>                                  
<div>   
<input type="radio" value="3" id="1" name="options" checked="checked"/>                         
<label for="1">B</label>
</div>                                  
<div>   
<input type="radio" value="4" id="2" name="options" checked="checked"/>                         
<label for="2">C</label>
</div>                                  
<div>   
<input type="radio" value="2" id="3" name="options" checked="checked"/>                         
<label for="3">D</label>
</div>              
<button type="submit">Next</button>             
</form>

1 个答案:

答案 0 :(得分:0)

单选按钮的使用方式没有意义。选定的单选按钮是单个值,但是您试图将其绑定到数组:th:field="*{options}"(而不是单个字段,例如th:field="*{selectedOpId}"之类)。

您的th:object上应该有一个字段,用于存储单选按钮选择的结果,而您的th:each应该在常规模型属性上进行迭代。像这样:

<form th:action="@{/dosomething}" th:object="${Object}" method="post">
    <th:block th:each="op : ${options}">
        <input type="radio" th:field="*{chosenOptionId}" th:value="${op.id}" th:id="${opStat.index}"/>                         
        <label th:for="${opStat.index}" th:text="${op.optiontext}">Option Text</label>
    <th:block>

    <button type="submit">Next</button>                 
</form>