I have a Spring-Boot project using Thymeleaf.
The HTML form has groups of fields for inputting personal details like:
<button type="button" class="btn btn-default" id="btnGetPerson"><i class="fa fa-search"></i></button>
<Input type="text" id="id0" name="id" th:field="*{person[0].id}" />
<Input type="text" name="surname" th:field="*{person[0].surname}" />
<Input type="text" name="firstname" th:field="*{person[0].firstname}" />
...
<button type="button" class="btn btn-default" id="btnGetPerson"><i class="fa fa-search"></i></button>
<Input type="text" id="id1" name="id" th:field="*{person[1].id}" />
<Input type="text" name="surname" th:field"=*{person[1].surname}" />
<Input type="text" name=firstname" th:field="*{person[1].firstname}" />
etc
The results are coming back from the server correctly as JSON and look like:
surname : Smith
firstname: Bob
Then in the script file I got as far as:
// GET AND RETURN PERSON
$( '#btnGetPerson').click(function() {
var $theForm = $(this).closest('.panel-body');
$.get('/person/' +$('#id0').val(), function(result) {
$theForm.find('input[name="surname"]').val(result.surname);
});
});
I was then going to do something like:
Object.keys(result).forEach(function(key) {
$('[name="' + key + '"]').val(result[key]);
});
To iterate over the keys and values in the JSON - but Thymeleaf renames the name fields in the HTML to match the form backing object, so my name="surname" gets over written with name="event.person[0].surname" where event is the backing object.
How should I approach mapping getting the JSON data that comes back from the server into the DOM?
UPDATE
A sample of the rendered html looks like:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Victim / Subject</h3>
</div>
<div class="panel-body">
<div class="row">
<input type="text" class="form-control hidden" id="personId0" name="persons[0].id" value="1" />
<div class="col-sm-5">
<div class="form-group">
<label for="surname0" class="col-sm-2 control-label">Surname</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="surname0" placeholder="surname" name="persons[0].surname" value="EASTWOOD"/>
</div>
</div>
</div
I should also add that the form initially renders with three people (index 0,1,2) and then there is a button to add another set of people fields dynamically by cloning the html fragment.