HTML supports boolean attributes such as checked
and disabled
, where:
The presence of a boolean attribute on an element represents the true
value, and the absence of the attribute represents the false
value.
The above spec gives three equivalent examples - which can be summarized (by me) as follows:
1
2
3
| <input type=checkbox checked>
<input type=checkbox checked=checked>
<input type='checkbox' checked="">
|
You can also mix the above styles.
The HTML5 standard is to just use checked
- but the other styles (using =
) are supported - I assume for backwards compatibility with older versions of HTML and maybe also for XHTML.
Unfortunately, the following also result in checked checkboxes - at least, in recent versions of Chrome, Firefox and Edge:
1
2
3
4
5
| <input type="checkbox" checked="false">
<input type="checkbox" checked="unchecked">
<input type="checkbox" checked="0">
<input type="checkbox" checked=anything>
<input type="checkbox" checked="anything">
|
So I think it’s important to try to stick to the officially sanctioned example(s).
When Thymeleaf is added to the mix, we can refer to their documentation here. Now, we are expected to provide an expression which evaluates to true
or false
:
1
| <input type="checkbox" name="active" th:checked="${user.active}">
|
Even for HTML5, the above example will generate an attribute like this:
checked="checked"
Which isn’t one of the officially sanctioned styles - but does also work as a variant of the checked=""
example.
Again we have to be careful. There is a wide range of Thymeleaf examples which will generate a checked checkbox.
Here are a few:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| <input type="checkbox" th:checked="${true}">
<input type="checkbox" th:checked="${'true'}">
<input type="checkbox" th:checked="${1}">
<input type="checkbox" th:checked="${''}">
<input type="checkbox" th:checked="${'1'}">
<input type="checkbox" th:checked="${'0'}">
<input type="checkbox" th:checked="${'checked'}">
<input type="checkbox" th:checked="${'anything'}">
<input type="checkbox" th:checked="${'null'}">
<input type="checkbox" th:checked="true">
<input type="checkbox" th:checked="'true'">
<input type="checkbox" th:checked="1">
<input type="checkbox" th:checked="'1'">
<input type="checkbox" th:checked="'0'">
<input type="checkbox" th:checked="checked">
<input type="checkbox" th:checked="'checked'">
<input type="checkbox" th:checked="anything">
<input type="checkbox" th:checked="'anything'">
|
And here are some Thymeleaf examples which all generate an unchecked checkbox:
1
2
3
4
5
6
7
8
9
| <input type="checkbox" th:checked="${false}">
<input type="checkbox" th:checked="${'false'}">
<input type="checkbox" th:checked="${0}">
<input type="checkbox" th:checked="${anything}">
<input type="checkbox" th:checked="${null}">
<input type="checkbox" th:checked="false">
<input type="checkbox" th:checked="'false'">
<input type="checkbox" th:checked="0">
|
Keep it simple to avoid confusion.