Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the id attribute of HTML element dynamically with Thymeleaf

Lets say I have an object : ${object}

and I have the following form:

<form id="{{'myForm' + object.id}" class="some class"       th:action="@{/doSomething}" method="post">     .... </form> 

My goal is to set the id = "myForm1" if we assume that the object.id is '1'.

PS: The way I wrote it's working on Angular JS.

like image 412
Lazar Lazarov Avatar asked Mar 01 '16 12:03

Lazar Lazarov


People also ask

How do you set the ID of an element in HTML?

The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id. The syntax for id is: write a hash character (#), followed by an id name.

What is the use of the html5 ID attribute?

The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).

How do I find id attributes?

You can use attr('id') in jQuery or the id property (or getAttribute('id') ) on the native DOM element. Show activity on this post. Show activity on this post. You can also use conventional .


2 Answers

You have to use th:id attribute:

<form th:id="'myForm' + ${object.id}" class="some class" th:action="@{/doSomething}" method="post"> // *** Other code here *** </form> 
like image 78
Sergio Garcia Alonso Avatar answered Sep 17 '22 18:09

Sergio Garcia Alonso


Here is how you can use dynamic id with label:

        <th:block th:with="randomId=${#strings.randomAlphanumeric(10)}">             <input type="checkbox" th:id="${randomId}">             <label th:for="${randomId}"></label>         </th:block> 
like image 25
rgrebski Avatar answered Sep 18 '22 18:09

rgrebski