sparrow
sparrow

Reputation: 1875

How to select a default option using thymeleaf

I have a drop down like following,

<select id="role" class="form-control" th:field="*{role}" >


    <option th:field="*{role}"  value="USER">USER</option>
    <option selected th:field="*{role}" value="ADMIN" >ADMIN</option>
    <option th:field="*{role}" value="SUPERUSER">SUPERUSER</option>


 </select>

I want default option as ADMIN. For that i added selected inside option tag. but default option still pointing to USER. Can anyone help me o solve this. Thanks

Upvotes: 0

Views: 4750

Answers (2)

Metroids
Metroids

Reputation: 20487

Set the value of "role" to "ADMIN" in your controller (in the java), before the page is rendered.

Also, you don't need all those extra th:field attributes. th:field should only appear on the select.

<select id="role" class="form-control" th:field="*{role}" >
    <option value="USER">USER</option>
    <option value="ADMIN" >ADMIN</option>
    <option value="SUPERUSER">SUPERUSER</option>
 </select>

Upvotes: 2

sparrow
sparrow

Reputation: 1875

I did something like following to get it working.

 <script th:inline="javascript">
            /*<![CDATA[*/
        window.addEventListener("DOMContentLoaded", function() {
            var optionSelected = [[${product.role}]];
            if(optionSelected == null){
                $("#role").val("ADMIN");
            } 

        });
        /*]]>*/
    </script>

and removed the selected attribute from the option.

Upvotes: 0

Related Questions