0

Here is the part of the code that I try to take out to .js file

$(document).ready(function () {
$("#buttonCancel").on("click", function () {
    window.location = "[[@{/users}]]"; 
});
});

and link to this file from .html right before close body tag:

<script type="text/javascript" th:src="@{/js/userForm.js?v=1}"></script>

If I click "Cancel" I have an error 400. Yes, I can use "window.location = "/myweb/users";" and it works well. But I am curious if there any way to use th-syntax in javascript file?

6
  • Looks l8ke you have several typos, th: is wrong as is the @{ and the }, should probably be <script type="text/javascript" src="/js/userForm.js?v=1"></script>, which is a relative path. If you are having trouble with it, replace it with a full http url Commented Jan 22, 2022 at 13:31
  • window.location should be a url. not -"[[@{/users}]]"; Commented Jan 22, 2022 at 13:35
  • Yes, I can use "window.location = "/myweb/users";" and it works well but the question is is there way to connect thymeleaf with javascript? Commented Jan 22, 2022 at 13:37
  • Hi @Tom what are tech stack are you using and what function do you need to perform? Commented Jan 22, 2022 at 13:54
  • 1
    You can do this... but you'd need to set up controllers for your JavaScript (the same way you have controllers for your HTML pages) and then treat your JavaScript files the same way (in a templates folder etc... they are no longer static resources). Commented Jan 22, 2022 at 17:20

1 Answer 1

1

As alternative, you could create a hidden link in your HTML, and then use it in your script:

HTML:

<a id="cancelAction" style="display:hidden" th:href="@{/users}"></a>

JavaScript:

$(document).ready(function () {
    $("#buttonCancel").on("click", function () {
        $("#cancelAction").click();
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.