Search code examples
spring-mvcinputdynamicthymeleafhref

Thymeleaf dynamic href using input value(s)


I understand that Thymeleaf templates are rendered server-side, but is there a simple way to reference input values client side to create an href dynamically?

Here is what I currently have:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>TEST</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Dynamic href</h1>
    <p>name:  <input type="text" name="name" /></p>
    <p>age:   <input type="text" name="age"/></p>
    <p>color: <input type="text" name="color"/></p>
    <a th:href="@{/userInfo(name='Americord',age='32',color='green')}">Submit</a>
</body>
</html>

Inside of my application controller I have:

@GetMapping(value = "/userInfo")
public String userInfo(@RequestParam(value = "name") String name,
                        @RequestParam(value = "age") String age,
                        @RequestParam(value = "color") String color) {

    // get user related user information
    return "success";
}

As you can see, right now the values for name, age & color are simply hard-coded. But I would like to reference the values from the input fields.

Maybe something like(?) :

<a th:href="@{/userInfo(name={name.value},age={age.value},color={color.value})}">
Submit
</a>

Solution

  • No, the only way to do this, is by using JS or jQuery. Thymeleaf once rendered, it simply can't modify anything else. Anyways, using jQuery is quite simple and you should make it work in no time. Something like the code below would do the trick.

    var ageInput = $('#age');
    var nameInput = $('#name');
    var url = $('#dynamic-url');
    
    ageInput.on('change', function() {
    
      if($(this).val() !== "" && nameInput.val() !== "") {
        url.attr('href', '/userinfo(age=' + $(this).val() + ', name=' + name.val() + ')');
      } else if ($(this).val() !== "") {
        url.attr('href', '/userinfo(age=' + $(this).val() + ')');
      } else if (nameInput.val() !== "") {
        url.attr('href', '/userinfo(name=' + nameInput.val() + ')');
      }
      
    });
    
    nameInput.on('change', function() {
      if($(this).val() !== "" && ageInput.val() !== "") {
        url.attr('href', '/userinfo(age=' + ageInput.val() + ', name=' + $(this).val() + ')');
      } else if ($(this).val() !== "") {
        url.attr('href', '/userinfo(name=' + $(this).val() + ')');
      } else if (ageInput.val() !== "") {
        url.attr('href', '/userinfo(age=' + ageInput.val() + ')');
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id="age" type="text" placeholder="age"/>
    <input id="name" type="text" placeholder="name"/>
    <a id="dynamic-url" href="/userinfo">
    Submit
    </a>

    Hope it helps!