Thymeleaf : passing javascript parameters

Viewed 18474

I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file. I want to pass an attribute of a POJO to a javascript function:

   <tr th:each="company: ${companies}" >                                                
         <td class="col_actions">
           <a th:href="@{/company/edit/{id}(id=${company.id})}" style="color:#808080; margin-right: 10px;">
             <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
           </a>
           <a href="#" style="color:#808080;  text-align: center;" onclick="javascript:confirmDelete ({id}(id=${company.id}));">
              <i class="fa fa-times" aria-hidden="true" ></i>
            </a>
         </td>
   </tr>

But I got an error: Uncaught SyntaxError: missing ) after argument list

4 Answers

Another way - th:onclick="|confirmDelete('${company.id}')|"

Or if you want send several params across '_' use th:onclick="|confirmDelete('${type}_${company.id}')|"

This works for me, easy and clear to use [[ ]]

Use a link:

<a href="#" id="editUserButton" th:onclick="editUser([[${user.getId}]])">Edit</a>

Use a button:

<button type="button" id="editUserButton" class="btn btn-primary"  th:onclick="editUser([[${user.getId}]])">Edit</button>

Pass multiple parameters:

<button type="button" id="editUserButton" class="btn btn-primary" th:onclick="editUser([[${user.getId}]],[[${user.getLastName}]])">Edit</button>

I found so many solutions that do not help me.

This is working for me.

<div class="add-to-cart">
    <button th:attr="onclick='addToBasket(\'' + ${product.getId()}+  '\');'"> add to basket
    </button>
</div>
Related