Search code examples
javaspringspring-mvcthymeleaf

How to select the value of a combo box in the controller in Spring MVC with Thymeleaf?


I have the following code for the view.

<input type="text" name="person" th:value="${person}">

<select name="gender" id="gender" th:value="${gender}">
    <option value="Male">Male</option>
    <option value="Female">Female</option>   
</select>

Controller

modelAndView.addObject("person", "Nancy");
modelAndView.addObject("gender", "Female");

When this runs, the person field correctly displays "Nancy". But the combo box displays male instead of female. How to make it show the correct value?


Solution

  • You need to use Thymeleaf to handle the selected attribute of each option, to ensure the initial display is correct:

    <select name="gender" id="gender" th:value="${gender}">
        <option value="Male" th:selected="${gender} == 'Male'">Male</option>
        <option value="Female" th:selected="${gender} == 'Female'">Female</option>   
    </select>
    

    This generates the following HTML:

    <select name="gender" id="gender" value="Female">
        <option value="Male">Male</option>
        <option value="Female" selected="selected">Female</option>   
    </select>
    

    The selected attribute is an HTML boolean attribute - Thymeleaf documentation for these is here.