Search code examples
thymeleaf

Thymeleaf: How to get selected item on click


I want to call a method with the clicked object as a param.

Problem: on every reload or button press the method is called for every element.

<form action="#" th:action="@{/}" th:object="${chessBoard}" method="post">
    <table>
        <tr th:each="i, iter1: *{board}">
            <td th:each="item, iter2: ${i}">
                <button th:onclick="${chessBoard.selected(item)}" th:text="${item.text}"></button>
            </td>
        <tr>
    </table>
</form>

Solution

  • You don't need the onclick method in your form to submit a parameter. You can simply pass a parameter to the controller with a RequestedParam annotation in your controller. It will be something like:

    <form th:action="@{/}" method="post">
      <table>
        <tr th:each="i: ${board}">
            <td th:each="item: ${i}">
                <button name="item" th:value="${item.id}" th:text="${item.text}"/>
            </td>
        <tr>
      </table>
    </form>
     
    

    and in your controller:

    @PostMapping (path = "/")
    public String test(Model model, @RequestParam(name = "item") int id) {
      System.out.println(id);
    }
    

    A second option is to use an attribute that you add to your model and you get back in your controller with something like:

    @PostMapping("/")
    public String greetingSubmit(@ModelAttribute ChessBoard chessBoard, Model model) {...}
    

    Html will be something like

    <form th:action="@{/}" th:object="${chessBoard}" method="post">
      <table>
        <tr th:each="i: ${board}">
          <td th:each="item: ${i}">
            <button th:field="*{id}" th:value="${item.id}" th:text="${item.text}"/>
          </td>
       <tr>
     </table>
    </form>