How to set radio button checked by default in Thymeleaf

Viewed 12050

I have group of 3 radio buttons. The user can choose only 1 of 3. I want to set a radio button chosen as default. I've tried this code but the checked attribute seems to be ignored.

    <div>
        <input type="radio" th:field="*{genre}" th:value="Strategy" checked="true">
        <label th:for="${#ids.prev('genre')}">Strategy</label>
    </div>
    <div>
        <input type="radio" th:field="*{genre}" th:value="RPG">
        <label th:for="${#ids.prev('genre')}">RPG</label>
    </div>
    <div>
        <input type="radio" th:field="*{genre}" th:value="Stealth">
        <label th:for="${#ids.prev('genre')}">Stealth</label>
    </div>

public class Game
{
    private String genre;
    //Constructor
    //Getter & Setter
}
2 Answers

In your controller, set genre = "Strategy" when Game is added onto the model.

Use JavaScript to get around this problem.

<input type="radio" id="optionsRadios1" name="category" th:field="${post.category}" th:value="option1">

<script>
document.getElementById("optionsRadios1").setAttribute("checked","checked")
</script>

Related