Thymeleaf - How to add checked attribute to input conditionally

mtyurt picture mtyurt · Apr 23, 2015 · Viewed 65.5k times · Source

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?

Answer

Faraj Farook picture Faraj Farook · Apr 28, 2015

According to the official thymeleaf documentation

http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#fixed-value-boolean-attributes

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

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

Where user.active should be a boolean.

So in your case it should be as Andrea mentioned,

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