【问题标题】:How to dynamically set HTML <input> names with Thymeleaf如何使用 Thymeleaf 动态设置 HTML <input> 名称
【发布时间】:2019-05-13 12:16:01
【问题描述】:

我有一个从控制器接收二维数组的表单,并且我已经通过 thymeleaf 生成了表格。

<div class="col-4 offset-4">
  <form id="sudokuBoard" method="post" enctype="application/x-www-form-urlencoded" class="form-group text-center">
    <div class="container">
      <table class="row-eq-height table-striped table-bordered text-center">
        <!--/*@thymesVar id="board" type=""*/-->
        <tr th:each="row: ${board}">
          <td th:each="value: ${row}">
            <div th:switch="${value}" class="col-xs-4">
              <input name="cellValue" th:case="0" class="content form-control input" style="text-align:center" type="text" pattern="[0-9]*" maxlength="1" value="0" onkeypress="return isNumber(event)" oninput="moveMade()">
              <input name="cellValue" th:case="*" class="content form-control input" style="text-align:center;background-color:lightgreen" type="text" th:value="${value}" readonly>
            </div>
          </td>
        </tr>
      </table>
      <div class="gap-10"></div>
      <button type="submit" class="btn btn-outline-primary btn-sm">Check Solution</button>
      <button class="btn btn-outline-primary btn-sm" id="btnNewGame">New Game</button>
      <button class="btn btn-outline-primary btn-sm" id="solveBoard"> Solve Puzzle</button>
    </div>
  </form>
</div>

所有输入字段都具有相同的名称,我想通过 Thymeleaf 动态分配名称,使它们变为cellValueX,以便区分每个单元格以检查用户输入的移动的有效性。

【问题讨论】:

    标签: javascript java html thymeleaf


    【解决方案1】:

    您使用属性th:nameSee this for a list of attributes you can use with Thymeleaf。我从你的代码中不知道你想在cellValueX 中为X 使用什么,但可能是这样的?

    <tr th:each="row, y: ${board}">
        <td th:each="value, x: ${row}">
            <input th:name="|cellValue${x.index}_${y.index}|" ... />
        </td>
    </tr>
    

    【讨论】:

    • 谢谢!这正是我想要的。我在玩th:name,但想不通。
    猜你喜欢
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多