I have this in my browser console (in fact, many similar messages):
[DOM] Found 2 elements with non-unique id #username: (More info: /* some URL */)
<input id="username" class="form-control" min="2" max="15" aria-describedby="uu-username-help-block" required="" name="username" value="scrooge_m">
<input type="hidden" id="username" name="username" value="scrooge_m">
But in my HTML there’s no <input type="hidden" id="username" name="username" value="scrooge_m">
. Instead, I have <input type="hidden" th:field="*{username}"/>
which was expected to translate into <input type="hidden" name="username" value="scrooge_m">
, no id
specified. I am afraid non-unique id
s may cause issues so I would like to resolve it
Does Thymeleaf’s th:field
generate an id attribute too? If so, how to I avoid these automatically generated id
s? If not, why do I not have these non-unique id
s in my IDE but have them in the browser?
ChatGPT 3 says th:field
doesn’t generate an id
, but Sage says it does
2
Answers
Yes, Thymeleaf makes a name for a form field, like "username," and it also makes an ID for it so the computer can remember it. If you don’t want Thymeleaf to make the ID, you can tell it what ID to use.
you can use the th:attr attribute to explicitly set the id attribute like this
You can see in the documentation what is generated when you use
th:field
:It generates the
id
,name
andth:value
.I wouldn’t give up the functionality of
th:field
because of the possibility of duplicateid
values. And if you are worried about them, yes you can specify the id in the tag. This works for example:Thymeleaf will not overwrite your id (or
th:id
, orth:attr="id='...'"
).