0

HTML

<form id="searchPersonForm" action="#" th:object="${person}" method="post">
<input type="text" class="form-control" id="person_id" th:field="*{person_id}"></input>
<input type="text" class="form-control" id="child_id" th:field="*{child_id}"></input>
</form>

How to assign dynamic id like person_id_100,person_id_200... and child_id_100, child_id_200... The values 100, 200 are actual person_ids.

Can we do without jQuery ?

Thanks in advance.

Java_User
  • 475
  • 2
  • 11
  • 30
  • possible duplicate of [Dynamically create divs with incremented id using jquery](http://stackoverflow.com/questions/7926484/dynamically-create-divs-with-incremented-id-using-jquery) – Chaitanya Gadkari Jun 22 '15 at 04:08
  • @ChaitanyaGadkari Thanks. But is it possible to do without jQuery. Like id="person + 'person_id'". – Java_User Jun 22 '15 at 04:13
  • 1
    Take a look at [thymeleaf forum]( http://forum.thymeleaf.org/How-to-get-id-values-dynamicaly-td4026516.html), there is a solution using th:each and a counter to set id for input elements. – Guillermo Jun 22 '15 at 04:26
  • @GuillermoFernández. Thanks. I will try the solution. – Java_User Jun 22 '15 at 07:17

1 Answers1

1

jQuery is probably worth learning if you plan on getting serious, but this can be done with a simple javascript file:

//saved as javascript.js

var formId = "searchPersonForm";
var inputArray = [];
for(var x=0;x < 10;x++){
    var newId = x*100
    var newInput = document.createElement("input")
    newInput.id = "person_id_" + newId
    inputArray.push(newInput);
}
for(var x=0;x < inputArray.length;x++){
    document.getElementById(formId).appendChild(inputArray[x])
    console.log(inputArray[x].id)
}

And just include the script in your page at some point after the form is instantiated:

<html>
<head>
</head>
<body>
<form id="searchPersonForm" action="#" th:object="${person}" method="post">
<input type="text" class="form-control" id="person_id" th:field="*{person_id}"></input>
<input type="text" class="form-control" id="child_id" th:field="*{child_id}"></input>
<script src="javascript.js"></script>
</form>
</body>

Output:

person_id_0
javascript.js:11 person_id_100
javascript.js:11 person_id_200
javascript.js:11 person_id_300
javascript.js:11 person_id_400
javascript.js:11 person_id_500
javascript.js:11 person_id_600
javascript.js:11 person_id_700
javascript.js:11 person_id_800
javascript.js:11 person_id_900
Jpaji Rajnish
  • 1,491
  • 4
  • 17
  • 35