How to add an attribute to element conditionally?

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

How to add an attribute to element conditionally?

apprentice
This post was updated on .
I need to display an attribute inside an element  e.g. <input  type="radio"  th:if="${sortBy == 'ASC'}" checked="true" /> 

The attribute "checked" should appear only if "sortBy variable is equal to "ASC".

Above if statement applies to the entire line which is not what I want.
Reply | Threaded
Open this post in threaded view
|

Re: How to add an attribute to element conditionally?

Metroids
In the case of a checkbox, it's as easy as:

<input type="checkbox" th:checked="${sortBy == 'ASC'}" />
Reply | Threaded
Open this post in threaded view
|

Re: How to add an attribute to element conditionally?

apprentice
I want the attribute checked to appear inside the element of just one radio button, rest of them will have no checked attribute.
Reply | Threaded
Open this post in threaded view
|

Re: How to add an attribute to element conditionally?

Metroids
So... did you actually try this? I actually tested it on thymeleaf (2.1.4)

Case 1:
Thymeleaf
<input type="checkbox" th:checked="${true}" />

Output
<input type="checkbox" checked="checked" />

Case 2:
Thymeleaf
<input type="checkbox" th:checked="${false}" />

Output
<input type="checkbox" />

Are you sure your condition "${sortBy == 'ASC'}" is evaluating correctly?