Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 437
mtyurt Avatar asked Apr 23 '15 14:04

mtyurt


3 Answers

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}" />
like image 67
Faraj Farook Avatar answered Nov 03 '22 04:11

Faraj Farook


After digging a little, I found out the solution. There is th:checked attribute for that purpose.

This works:

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

This fails:

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

If checked="" is set to input component, it's marked checked. This method is valid for custom attributesth:attr also. Consider following example:

<p th:attr="customattr=${flag}?'attr'></p>

If flag is true, it's replaced with:

<p customattr="attr"></p>

If flag is false, it's replaced with:

<p></p>
like image 40
mtyurt Avatar answered Nov 03 '22 06:11

mtyurt


You can conditionally add checked attribute to radio input in thymeleaf as below:

 <input type="radio" th:checked="${sales.sales_head.sales_type} == CREDIT" class="sales_type" value="CREDIT"  name="sales_type" >

Here if sales_type is CREDIT the radio will be checked. Otherwise it remains unchecked.

like image 2
Ameera Najah Kv Avatar answered Nov 03 '22 04:11

Ameera Najah Kv