Search code examples
spring-bootthymeleafdropdown

th:selected for select tag in Thymeleaf not working


<select multiple="multiple>

<option th:each="vName : ${variety}"

th:value="${vName}"

th:text="${vName}"

th:selected="${selectedVariety}"></option> 

</select>

In the above code "selectedVariety" is a string array sent from controller.

I'm not able to bind the select tag on edit.

And this select tag is not a part of entity table so th:filed="*{selectedVariety}" is not working.

Tried th:attr="selected=${selectedVariety==vName?true:false}">

Not working

On using this "th:selected="${selectedVariety}" every option in the dropdown is getting selected.

What may be the solution??


Solution

  • The option is selected when the value is included to the String array. You'll need following attribute within your <option>:

    th:selected="${#arrays.contains(selectedVariety, vName)}"
    

    It returns true (selected) if selectedVariety contains given vName or false (unselected) otherwise.