JS - Attach the same function to many html forms

Viewed 156

I am trying to make an e-commerce-like webpage (for practice) wherein a click on any of the buttons would update the cart value by the number (quantity) specified on the input element. So far, I was only able to update the cart from the first form because when I try to assign the function on every form using a loop, the cart updates for a millisecond then returns to zero. I assume its because of the scope. I know there's an easier way to do this without manually assigning the function for every document.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'm only posting 1 form example, but in reality, 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>
3 Answers
Related