This question already has an answer here:
I'm building an app with Spring Boot, the MVC pattern, and Thymeleaf as template engine. I have a form that generates a list with Javascript, and a controller with a @ModelAttribute expecting a list, to be saved into the database.
At the Javascript side I collect the items with this array:
groupList = [];
groupList.push(inputValue);
function getGroupList(){
return groupList;
}
In the html I'm trying to assign the array value to a hidden input field:
<input type="hidden" class="invisible" id="groupList" th:field="*{groupList}"/>
With this inline function:
<script th:inline="javascript" type="text/javascript">
$(function() {
var groupListCollected = getGroupList();
$("#groupList").val(groupListCollected);
});
</script>
My problem at this point, is that I don't find the way to collect the array, and pass it to the Controller as a list.
This is the value that the console shows, for the input field:
<input type="hidden" class="invisible" id="groupList" name="groupList"
value="[object HTMLInputElement]">
Any advice to face this issue, would be much appreciated. Thanks in advance.
You can proceed like this : Create a Model, for exemple:
Create a FormModel:
in your controller (Get and Post) :
In my view (hello.html) : for listing all users :
Now if I want to add another user with javascript when I clic in the button 'ADD, I will append() a new 'li' element containing the new user :
When I Submit, I will get a list with 2 User : 'Wassim' & 'Rafik'. You can manage this exemple (also the index of the list must managed properly) to append your list with the needed DATA.