Nimchip
Nimchip

Reputation: 1735

Variable expression into javascript without using th:inline

I searched first but I found confusing answers since I'm new to Thymeleaf and amateurish at best at javascript.

I just want to know how to pass variable expressions into javascript functions, sort of like in JSP:

<a href="#" onclick="javascript:getContactId('${contact.id}');">Button</a>

Of course, this fails with Thymeleaf and passes the string ${contact.id} instead of its value, so how could I get the value of the variable expression instead?

The reason I want it this way is because it depends on the row which is being iterated by th:each.

If there's no other way except to use th:inline, then what's the best approach considering the above statement?

Upvotes: 11

Views: 26607

Answers (6)

Jason Hapyer
Jason Hapyer

Reputation: 25

I have asked the Thymeleaf project on twitter, and their answer is:

You can use both the "+" operator or literal substitutions. For example: <a th:href="|javascript:change('start','${taskId}')|">

For more info: https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html

I have tried, and it works~

Upvotes: 0

wi2ard
wi2ard

Reputation: 1545

A more generic approach, if you need in JS something that isn't passed as a event handler parameter:

th:attr="data-myValueFromThymeleaf=${contact.id}"

Any attribute whose name is starting with data- is ignored by all browsers. So it won't affect the UI and you can easily read the value in javascript.

I prefer this because it's not ideal to put javascript code in html (see unobtrusive javascript)

Upvotes: 0

David V
David V

Reputation: 11699

In Thymeleaf version 2.1, I have not been able to get the accepted answer to work. I did find some guidance from a Twitter post from Thymeleaf. Rather than using th:onclick, you use th:attr and specify the onclick attribute therein.

th:attr="onclick='javascript:getContactId(\'' + ${contact.id} + '\');'"

Upvotes: 6

user3029929
user3029929

Reputation: 491

You can do this like:

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

Upvotes: 0

Nimchip
Nimchip

Reputation: 1735

This one worked:

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

Thanks goes out to the thymeleaf forum: http://forum.thymeleaf.org/variable-expression-into-javascript-without-using-th-inline-td4025534.html

Upvotes: 29

Archer
Archer

Reputation: 5147

You can not put javascript variables into onclick or other DOM attributes. The value of onclick or any other DOM attribute should be a constant string.

However, you can dynamically modify value of onclick attribute from javascript, like this:

yourDomElement.onclick = anyVariable;

Upvotes: 0

Related Questions