skip to Main Content

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 ids 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 ids? If not, why do I not have these non-unique ids 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


  1. 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

    <input type="hidden" th:field="*{username}" th:attr="id='my-username'"/>
    Login or Signup to reply.
  2. You can see in the documentation what is generated when you use th:field:

    <input type="text" th:field="*{datePlanted}" />
    

    As you can see, we are introducing a new attribute here: th:field. This is a very important feature for Spring MVC integration because it does all the heavy work of binding your input with a property in the form-backing bean. You can see it as an equivalent of the path attribute in a tag from Spring MVC’s JSP tag library.

    The th:field attribute behaves differently depending on whether it is attached to an , or tag (and also depending on the specific type of tag). In this case (input[type=text]), the above line of code is similar to:

    <input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />
    

    It generates the id, name and th:value.

    I wouldn’t give up the functionality of th:field because of the possibility of duplicate id values. And if you are worried about them, yes you can specify the id in the tag. This works for example:

    <input id="unique-id-here" type="hidden" th:field="*{username}"/>
    

    Thymeleaf will not overwrite your id (or th:id, or th:attr="id='...'").

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search