【问题标题】:Thymeleaf Radio button th:field checked validationThymeleaf 单选按钮 th:field 检查验证
【发布时间】:2019-10-17 18:51:12
【问题描述】:

我正在尝试验证使用 th:each 创建的单选按钮的输入。 在 html 中的输入输出中使用 th:field 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>

【问题讨论】:

    标签: thymeleaf


    【解决方案1】:

    您使用单选按钮的方式没有意义。选择的单选按钮是单个值,但您尝试将其绑定到数组: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>
    

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 2012-12-28
      • 2021-09-25
      • 2018-05-24
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 2016-02-15
      • 2011-11-26
      相关资源
      最近更新 更多