How to select element with Thymeleaf attribute?

I have an HTML page with the following element:

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

I want to select this element by attribute with jQuery function, like this:

$("[th:field='*{recipientName}']")

However, I get this error:

Uncaught Error: Syntax error, unrecognized expression: [th:field='*{recipientName}']

How can I select this element and what am I doing wrong?

Answers 1

  • I believe your problem is that the colon : is not valid in an attribute name, so the selector fails to return anything. If you're unable to change the name of the selector (i.e. if the colon is a Thymeleaf requirement), you will have to add an alternate identifier.

    Maybe put the whole field name and value into a data- attribute? e.g.

    <input type="text" data-somevar="th:field=*{recipientName}" th:field="*{recipientName}"/>

    And then select it like this:

    $("[data-somevar='th:field=*{recipientName}']");

    Update: I have had a play around with it and it appears it is possible if you escape the colon when passing it to jQuery, so this should work:

    $("[th\\:field='*{recipientName}']");

    Codepen example.

    I'll leave the previous answer/explanation in case anyone else finds it useful.


Related Articles