Gururaj Mb
Gururaj Mb

Reputation: 111

Thymeleaf onclick send td value to javascript function

I am using "Thymeleaf", I want to send the value to javascript, I am new to this, I am trying below code:

onclick="getPropId('${properties.id}')"

and function

getPropId(inputID){alert(inputId);}

But I am not getting actual value.

Upvotes: 3

Views: 18329

Answers (5)

William
William

Reputation: 43

Future visitors,

Let me introduce you to a easier way of doing it.

Yes you can do it with ' or with | or even with [[]] but the question is: Is it clean and easy to implement?

Most of us will waste more than 10 minutes to try to figure out the correct way to use '',,|| to make this line work.

Why not simply add data-attributes for each param and use it on the function? Something like this:

<button th:data-param1="${value}" th:data-param2="${value2}" onclick="call(this);"/>

Then the function:

<script>
  function call(e){
    const param1 = e.dataset.param1;
    const param2 = e.dataset.param2;
  }
</script>

I let you judge the better way of doing it, but keep in mind that someone may pass after you and read your code. So always try to keep it readable and easy to maintain.

Upvotes: 0

Ashish
Ashish

Reputation: 11

i solved the same problemm by declaring th:attribute

<div class="row" th:each="data,i : ${obj}">
    <a href="javascript:void(0);" th:attr="onclick='loadDetails(\'' + ${data.objId}+'\')'">
</a>
</div>

Upvotes: 1

coms
coms

Reputation: 479

Cleaner with literal substitution ||:

th:onclick="|getPropId('${properties.id}');|"

Multiple case:

th:onclick="|getPropId('${var1}','${var2}');|"

Upvotes: 1

Prabhat
Prabhat

Reputation: 143

For passing multiple parameters, you can use the following:

th:onclick="'doSomething(\''+${val1}+ '\',\''+${val2}+'\',\''+${val3}+'\');'"

Upvotes: 3

Gururaj Mb
Gururaj Mb

Reputation: 111

Above issue is resolved now, we need to use Thymeleaf specific syntax.

th:onclick="'getPropId(\'' + ${properties.id} + '\');'"

Now if its displying proper properties.id in javascript function.

function getPropId(inputID){
    alert(inputID);
}                           

Upvotes: 8

Related Questions