Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set radio button checked by default in Thymeleaf

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
}
like image 915
tony Avatar asked Oct 18 '25 15:10

tony


2 Answers

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

like image 175
Metroids Avatar answered Oct 21 '25 16:10

Metroids


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>

like image 40
Jin Lim Avatar answered Oct 21 '25 15:10

Jin Lim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!