Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a variable from thymeleaf to a javascript function?

I have an html file, thymeleaf, that has a variable passed from the controller that I need to give to a function on an external javascript file. How do I do this ?

I can get the variable like

<label th:utext="${id}" ></label>

I need to pass that id to a function that's inside

<script th:src="@{/js/myfunctions.js}" type="text/javascript"></script>

There's a function there :

function myFunction(id){

}

2 Answers

You can do something like this :

<input type="hidden" id="yourId" th:value="${id}"/>

Then in your js function :

function myFunction(){
 var val = $("#yourId").val();
}

Note that I use Jquery but the principe is the same.

If the JS function code is in your html page (not .js external file) you can access the model value like this :

function myFunction(){
  var val = "${id}";
}
like image 153
akuma8 Avatar answered Jul 15 '26 20:07

akuma8


Inline HTML example:

th:onclick="${'myFunction(' + id + ');'}"

like image 23
Nicolette Halsema Avatar answered Jul 15 '26 20:07

Nicolette Halsema



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!