0

I am trying to build a table using th:each and have the whole row of the table clickable as a link through JavaScript.

<table>
    <th:block th:each='user : ${list}'>
        <script th:inline="javascript">
            var userid = [[${user.id}]];
        </script>
        <tr onclick="location.href='user?id='+userid">
            <td th:text="${user.firstName}"></td>
            <td th:text="${user.lastName}"></td>    
        </tr>
    </th:block>
</table>

However, the variable always refers to the latest value and not the one it was when the row was created. Is there a way to do that? Or maybe a different solution to what I'm trying to do?

asd
  • 3
  • 1

2 Answers2

0

You can avoid using JavaScript by adding an <a> element to each table cell (Inspired by https://stackoverflow.com/a/17147909/40064):

<table>
    <th:block th:each='user : ${list}'>
        <tr>
            <td><a th:href="@{/user(id=${userid})}" th:text="${user.firstName}"></a></td>
            <td><a th:href="@{/user(id=${userid})}" th:text="${user.lastName}"></a></td>    
        </tr>
    </th:block>
</table>
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
  • That is what I am currently doing, but it has the link only on the text and not the entire row. – asd Sep 13 '22 at 12:52
  • If you use padding like this: `td a {padding:16px}` And `border-spacing:0;` and `border-collapse: collapse` on the `table` then it should like you can click the row. – Wim Deblauwe Sep 13 '22 at 13:08
0

No need for the th:block, you can simply put the th:each on the tr.

To accomplish the click, I recommend putting the id in a data attribute, and retrieving it in JavaScript. This should work for you:

<table>
    <tr th:each="user : ${list}"
        th:data-id="${user.id}"
        onclick="location.href = 'user?id='+this.getAttribute('data-id')">
        <td th:text="${user.firstName}"></td>
        <td th:text="${user.lastName}"></td>    
    </tr>
</table>
Metroids
  • 18,999
  • 4
  • 41
  • 52