protrafree
protrafree

Reputation: 96

Add Variable inside th:onsubmit thymeleaf

I'm trying to add variable inside th:onsubmit with

th:onsubmit="return confirm('Hi '" + ${user.name} +  "')"

but it always get me error like

Malformed markup: Attribute "+" appears more than once in element

also i can't find onsubmit example on thymeleaf official document

Upvotes: 2

Views: 2190

Answers (2)

Metroids
Metroids

Reputation: 20487

There is nothing special about onsubmit which is why there is nothing in the official documentation about it -- you're simply not formatting the expression correctly. I would format the expressions like this:

th:data-username="${user.name}"
onsubmit="return confirm('Hi ' + this.getAttribute('data-username'))"

(To avoid security errors, Thymeleaf may prohibit you from concatenating strings directly in your JavaScript, which is why I'm separating it out to it's own attribute.)

Upvotes: 4

andrewJames
andrewJames

Reputation: 21914

You can use a function in your onsubmit event, and assign the Thymeleaf expression to a variable within that function.

Example (using onclick in my case):

<yourtag ... onclick="runMyFunction();"></yourtag>

...

<script th:inline="javascript">
    function runMyFunction() {
        var user_name = [[${user.name}]];
        console.log(user_name);
    }
</script>

This uses Thymeleaf's JavaScript inlining syntax [[${...}]].

Note that in this case, the event does not have to be th:onsubmit - just onsubmit.

Upvotes: 0

Related Questions