'Is there a simple way of using the th:data* and th:each attributes together in Thymeleaf?

My intention is to obtain an object inside one of the rows of the table, so I could forward it to a form using a simple JavaScript function. I am not familiar with jQuery so I thought I’ll take an as-simple-as-possible approach. I was thinking of doing this by using the th:data* attribute in combination with th:each, like this:

<tr th:each="employee : ${empDetailsList}" th:data-employee="${employee}">
    <td scope="row" th:text="${employee.id}">ID</td>
    <td scope="row" th:text="${employee.firstName}">firstName goes here</td>
    <td scope="row" th:text="${employee.lastName}">lastName goes here</td>
    <td scope="row" th:text="${employee.email}">email goes here</td>
    <td scope="row" th:text="${employee.username}">user name goes here</td>
    <td th:data-employee="${employee}">
        <button type="button" class="btn btn-info" th:onclick="showEditForm(this.getAttribute('data-employee'));">Details</button>
</tr>

I also tried this approach, moving the th:data-employee from the 'tr' tag to the 'td' tag but the result is the same:

<tr th:each="employee : ${empDetailsList}">
...
    <td th:data-employee="${employee}">
        <button type="button" class="btn btn-info" th:onclick="showEditForm(this.getAttribute('data-employee'));">Details</button>
</tr>

The JS function:

function showEditForm(employee){
        console.log('Employee object here: ');
        console.log(employee.firstName);
        console.log(employee.lastName);     
    }

As I mentioned I get the same result in both cases. The browser consoles response is:

Employee object here:
TypeError: employee is null

So, what am I doing wrong here?



Solution 1:[1]

This worked for me:

 <p th:each="testScript:${testScripts}">
            <a  th:href="|/scripts/start/${testScript}|" th:text="'Start '+ ${testScript}"/>
            <a  th:href="|/scripts/stop/${testScript}|" th:text="'Stop' + ${testScript}"/>

            <button id="searchButton" name="searchButton" th:onclick="start(this.getAttribute('data_p1'));" type="button"
                    th:data_p1="|${testScript}|"
                   th:text="|${testScript}|">Start</button>
        </p>   

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roland Roos