springspring-mvcthymeleaf

th:selected a number in a select/option with Thymeleaf doesn't work


I have this code

<div th:class="form-group">
    <td><label class="control-label leftMargin10 rightMargin10" scope="col" th:text="#{insertHours.hhFrom}">Attivita'</label></td>
    <td><select class="form-control" th:field="*{hhFrom}">
        <option th:each="i : ${#numbers.sequence(0, 23)}" th:value="${i}" th:text="${i}" th:selected="${ i==9 } ">Options</option>
    </select>
    </td>
</div>

When I try to add a condition in th:selected it doesn't work.

I have also replaced with this code:

th:attr="${i==9}? selected=selected: '' "

but the result is the same.

The HTML

<select class="form-control" id="hhFrom" name="hhFrom">
    <option value="0" selected="selected">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12</option>
    <option value="13">13</option>
    <option value="14">14</option>
    <option value="15">15</option>
    <option value="16">16</option>
    <option value="17">17</option>
    <option value="18">18</option>
    <option value="19">19</option>
    <option value="20">20</option>
    <option value="21">21</option>
    <option value="22">22</option>
    <option value="23">23</option>
</select> 

Thanks in advance to answers


Solution

  • You cannot use th:field along with th:selected. If you replace th:field with name=someMeaningfullName the code will work just fine.

    Check out this thread on the Thymeleaf forum for more information