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

后端 未结 3 711
南旧
南旧 2021-02-07 09:21

I have this code

相关标签:
3条回答
  • 2021-02-07 10:00

    Also I found out that if you put <div> tag around option fields, selected="selected" will also work. e.g

    <select th:field="*{name}">
        <div>
            <option disabled="true" selected="selected" value="">Select</option>
            <option value="1">first</option>
            <option value="2">second</option>
        </div>
    </select>
    
    0 讨论(0)
  • 2021-02-07 10:13

    Another hack that, is pretty simple and works, is to close the select tag: <select ... />

    Please note /> at the end of first line:

    <select th:field="*{percentage}" />
        <option th:each="i : ${#numbers.sequence(0, 100)}" th:value="${i}" th:text="${i}" th:selected="${i==75}"></option>
    </select>
    

    Renders as:

    <select id="percentage" name="percentage" />
        <option value="0">0</option>
        <option value="1">1</option>
        ...
        <option value="74">74</option>
        <option value="75" selected="selected">75</option>
        <option value="76">76</option>
        ...
        <option value="100">100</option>
    </select>
    

    Both web browser and Thymeleaf will handle this fine.

    I used Thymeleaf v.3.0.9.RELEASE

    0 讨论(0)
  • 2021-02-07 10:17

    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

    0 讨论(0)
提交回复
热议问题