3

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){

}

5 Answers5

4

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}";
}
akuma8
  • 4,160
  • 5
  • 46
  • 82
3

Inline HTML example:

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

  • I have an use case where id needs to be resolved like '1234' (with the single quotes) any idea how that can be done. – p.k Mar 12 '22 at 01:32
  • 1
    @p.k `aaaa` should do it When I inspect element I see: `aaaa` – V H Apr 19 '22 at 15:49
3

try this: (a bit late to the party)

<script type="text/javascript" th:inline="javascript">

th:attr="onChange=|yourFunction(${id})|" </script>
Robert T.
  • 31
  • 1
2

Pass a variable like that:

<script th:inline="javascript">myFunction(/*[[${id}]]*/);</script>
RoM
  • 76
  • 1
  • 6
0

This is an example:

//for parameter
function myfunction ([[${id}]]){
    //this is for address rout 
    window.location=[[@{/user}]]
}

use [[]] and put thymleaf expression

General Grievance
  • 4,555
  • 31
  • 31
  • 45