Search code examples
ajaxspring-bootcheckboxthymeleaf

SpringBoot + Thymeleaf dinamic table with checkbox in row communicate with Controller


Maybe the title is more confusing than the problem it self. Here's my situation, with Thymeleaf I show a table with a list of clients. It shows Name, LastName, a button to delete it and a checkbox to display it's state (if the user is active or inactive)

<table class="table">
<thead>
<tr>
    <th>Name</th>
    <th>Last Name</th>
</tr>
</thead>
<tbody>
<tr th:each="client : ${clientList}">
    <td th:text="${client.name}"></td>
    <td th:text="${client.lastName}"></td>
    <td>
        <a th:href="@{/delete_client/} + ${client.id}" class="btn btn-danger">Delete</a>
    </td>
    <td>
        <input type="checkbox" name="my-checkbox" th:checked="${client.state} ? 'checked'">
    </td>

</tr>
</tbody>

So far, no problem. But what I don't know how to do is communcate the controller when the user click the checkboxes, in order to disable or enable that particular client.

Something like what the button does to delete the client, but to change it's state.

I was told to use AJAX, but don't know how.

Thank you!


Solution

  • You can avoid ajax. For deleting-alike effect you can apply following steps to the td element containing a checkbox:

    • wrap up the checkbox in the form tag
    • provide the proper action attribute in the form. The action is an endpoint which handles updating of a client's state (similarily to/delete_client/)
    • provide onclick="submit();" attribute in the checkbox, which will trigger mentioned endpoint when the user clicks it

    E.g.

    <td>
        <form th:action="@{/switch_client_state/} + ${client.id}">
            <input type="checkbox" name="my-checkbox" onclick="submit();" th:checked="${client.state} ? 'checked'">
        </form>
    </td>