Pass a variable from thymeleaf to a javascript function?
12,881
Solution 1
Inline HTML example:
th:onclick="${'myFunction(' + id + ');'}"
Solution 2
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}";
}
Solution 3
Pass a variable like that:
<script th:inline="javascript"}">myFunction(/*[[${id}]]*/);</script>
Solution 4
try this: (a bit late to the party)
<script type="text/javascript" th:inline="javascript">
th:attr="onChange=|yourFunction(${id})|" </script>
Related videos on Youtube
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 04, 2022Comments
-
Admin about 2 years
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){ }
-
RK Shrestha over 3 yearsdo as th:onclick="myfunction('[[(${id})]]')"
-
Mike D3ViD Tyson over 3 yearsseems to be already answered here stackoverflow.com/a/25688291/6157415
-
-
James Grey about 5 yearsI cannot do like this
var val = "${id}";
-
Chris Sum over 3 yearshow can assing to an external file without assign in the html a big json?
-
p.k over 2 yearsI have an use case where id needs to be resolved like '1234' (with the single quotes) any idea how that can be done.
-
V H about 2 years@p.k
<span th:attr="onclick=${'doThis('+ '''' + user.getTestJquery() + '''' + ')'}">aaaa</span>
should do it When I inspect element I see:<span onclick="doThis('presetValue')">aaaa</span>