I have a basic HTML post form like this:
<ul>
<li>
<input type="radio" th:field="*{type}" th:value="'Flight'" name="flight" id="flight" checked>
<label for="flight" th:text="'Flight'"/>
</li>
<li>
<input type="radio" th:field="*{type}" th:value="'Bus'" name="bus" id="bus">
<label for="bus" th:text="'Bus'"/>
</li>
<li>
<input type="radio" th:field="*{type}" th:value="'Personal'" name="personal" id="personal">
<label for="personal" th:text="'Personal'"/>
</li>
</ul>
I am trying to take input from radio buttons but checked
method is not working:
But when I remove the th:field
method, it works fine:
What am I doing wrong in here?
CodePudding user response:
I'm pretty sure th:field
overwrites the checked attribute. To get a default radio to be checked there are 2 solutions I believe.
- pre-fill your
th:object
bean with the default value. When this is the caseth:field
should automatically check the correct radio. - Use javascript to check the radio button after rendering
P.S. when setting static string as value you can just use value="Bus"
no need to write th:value="'Bus'"
CodePudding user response:
I don't know if this is a valid solution but:
private String type = "Flight";
setting my type = "Flight"
in my controller solved it.