Search code examples
javascriptspringspring-bootspring-mvcthymeleaf

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


Solution

  • 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.)