Search code examples
htmlspring-bootspring-mvcthymeleaf

How can I perform an action after selecting an Option on a Select using Thymeleaf?


I'm trying to redirect my page when selecting an Option on a Select using Thymeleaf. My code is written as follows:

<select>
    <option th:each="size : ${pageSizes}" th:text=${size}  th:onclick="'window.location.href = \'' + @{/ingredient(size=${size})} + '\''"></option>
</select>

And, after inspecting it on Google Chrome, the HTML created is:

<select>
    <option onclick="window.location.href = '/ingredient?size=5'">5</option>
    <option onclick="window.location.href = '/ingredient?size=10'">10</option>
    <option onclick="window.location.href = '/ingredient?size=20'">20</option>
    <option onclick="window.location.href = '/ingredient?size=25'">25</option>
    <option onclick="window.location.href = '/ingredient?size=50'">50</option>
</select>

But nothing happens when a select a new Option. What am I doing wrong?


Solution

  • Use onchange event on select tag instead of onclick.

    <select th:onchange="'window.location.href = \'' + @{/ingredient} + '?size=\' + this.value ' ">
        <option th:each="size : ${pageSizes}" th:text=${size}  ></option>
    </select>