I am trying to create a web page similar to e-commerce (for practice), in which clicking on any of the buttons updates the basket value by the number (quantity) indicated on the input element. Until now, I could only update the basket from the first form, because when I try to assign a function in each form with a loop, the basket updates for the millisecond then return to zero. I guess it is due to volume. I know that there is an easier way to do this without manually assigning a function to eachdocument.forms[n]
Js
window.onload = function()
{
var getForm = document.forms[0];
var numItems = 0;
getForm.onsubmit = function(event)
{
event.preventDefault();
var getInput = getForm.elements["num-item"].value;
if(parseInt(getInput))
{
numItems = numItems + parseInt(getInput);
var getCart = document.getElementById("item-count");
getCart.innerHTML = numItems;
getForm.reset();
}
else
{
alert("Please enter a valid number");
}
}
HTML
Cart:
<div class="basket">
<p><i class="fa fa-shopping-basket"></i></p>
<p id="item-count">0</p>
</div>
HTML Form . For brevity, I publish only one example of a form, but in fact I have 6 other forms that are exactly the same.
<div class="buy-config">
<form class="buy-form" name="buy-form">
<label>Quantity:</label>
<input type="text" class="num-item" />
<button class="buy-btn">Add to Cart</button>
</form>
</div>