This is simple java class that has a list of strings for example:
public class Apple {
private List<String> listOfStrings;
// getters setters
}
html with thymeleaf:
<form method="post" th:object="${apple}"> // apple is set through Model.addAttribute(.., ..) in Controller
<input type="text" th:each="str, iter : *{listOfStrings} th:field="*{listOfStrings[__${iter.index}__]}">
<button id="add" type="button" onclick="add()>Add</button>
<button id="remove" type="button" onclick="remove()">Remove</button>
<input type="submit" value="Save">
<form>
javascript add and remove new input:
const newInputTextString="<input type=\"text\" th:field="?">" // th:field won't be evaluated/bound to apples listOfStrings index
function add() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("add").insertAdjacentHTML("beforebegin", newInputTextString);
}
xhttp.open("GET", window.location.href);
xhttp.send();
}
function remove() {
// TODO
}
So far I am only adding html through javascript, but I can not include th: tags there since these tags wont be evaluated and bind to specific object or fields.
Expected functionality:
- on click of remove button, last input of type text that is bound to specific index of listOfStrings is removed.
- on click of add button, new input of type text is added and bound to next index of listOfStrings.
In other words I want to make user able to remove and add strings in listOfStrings of that apple object with html buttons.
Feel free to correct my English