Home > Enterprise >  th:field is braking checked method in html input field
th:field is braking checked method in html input field

Time:08-15

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:

enter image description here

But when I remove the th:field method, it works fine:

enter image description here

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.

  1. pre-fill your th:object bean with the default value. When this is the case th:field should automatically check the correct radio.
  2. 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.

  • Related