Search code examples
javascriptjqueryspring-bootthymeleaf

Thymeleaf / JavaScript keep value of dynamically populated select element


I have two dropdowns (select elements). First represents categories (populated from Thymeleaf model attribute), second: items for the chosen category (it is populated based on the value of the first select using jQuery Ajax). I want to keep both values after submitting the form. For the first dropdown it is easy (th:selected with usersCategory model attribute which is added by the Spring Controller):

<select id="someCategory" name="someName"> 
<option th:each="category : ${categories}" th:value="${category.id}" th:selected="${category.id}==${usersCategory}" th:text="${category.longName}"></option
</select>

But the second drop down is dynamically populated, so the html is only:

  <select id="someItems" name="someItemsName">
  </select> 

I don't know how to keep the value of the second dropdown using just Thymeleaf/JavaScript/jQuery (without cookies, additional libraries etc.). I tried using inline expressions to get model attribute, but setting the value of the second dropdown did not work this way.


Solution

  • I actually made it work by using the inline expressions as described in Thymeleaf docs link to access the model attribute. Just had to make sure that I set the value of select element after Ajax request and not within the inline script.