Thymeleaf – How to add checked attribute to input conditionally


As you know, input component has an attribute, checked to whether mark the checkbox as enabled by default or not.

<input type="checkbox" name="mycheckbox" checked="checked"/>

To disable the checkbox by default, the checked exception should be declared. Is it possible to set checked attribute by a flag in Thymeleaf?


According to the official thymeleaf documentation

th:checked is considered as a fixed-value Boolean attribute.

<input type="checkbox" name="active" th:checked="${}" />

Where should be a boolean.

So in your case it should be as Andrea mentioned,

<input type="checkbox" name="mycheckbox" th:checked="${flag}" />

Answered By – Faraj Farook

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.