Hello,
i have a little problem that maybe you could help me with. I searched the internet for quite a long time but i didn't find any answers.
I have a little web shop using Spring and Thymeleaf. My task is now to implement the option to change the quantity of a cart item inside the cart. This value is stored in a variable ${item.quantity}.
So in conclusion if I press "up" or "down" on the input field, the item in the cart should change its quantity and the total price of all cart items should be evaluated again.
I used an <input type="number"> combined with an onchange event running a javascript function, but all my tries went wrong.
Here is the code snippet of cart.html template:
<input
type="number"
onchange="change(this.value)"
min="1"
max="5"
th:value="${item.quantity}"
>
And this is my javascript code:
<script th:inline="javascript">
/*<![CDATA[*/
function change(data) {
var quantity = /*[[${item.quantity}]]*/ data;
location.reload(false);
}
/*]]>*/
</script>
but this doesn't work.
Hopefully you understand what I mean and someone can help me, because I really don't have any idea how to else do this.
You need to send the changed quantity back to the server. As a first step do it without JavaScript. Use a simple form, for example:
<form action="/change-quantity">
<input type="hidden" name="itemId" th:value="${item.id}">
<input type="number" min="1" max="5" th:value="${item.quantity}">
<input type="submit" value="Update">
</form>
Now you need to write a POST controller for the path /change-quantity that looks up the item by the ID, change it's quantity and finaly redirects back to the page you came from.