11

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

0

4 Answers 4

13

The problem came from anchor, so please try this one if the confirmDelete() function require a string id

th:onclick="'javascript:confirmDelete(\'' + ${company.id} + '\');'"

And if it need a number id

th:onclick="'javascript:confirmDelete(' + ${company.id} + ');'"
Sign up to request clarification or add additional context in comments.

1 Comment

Might not work for the latest version of thymeleaf, please refer the answer I posted to a similar question stackoverflow.com/a/64884416/5105263
8

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

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

Comments

5

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>

Comments

4

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>

1 Comment

OMG... thank goodness... I too have found innumerable "solutions" to this problem and none of them worked... except for this one. This is the very best answer to this question of how to pass a model variable from Thymeleaf to a JavaScript function. Applause.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.