I am trying to set it so that if I click on a button with the class of "addtocart" it will check the id of the button in the HTML document and iterate through the products array objects until it finds the object with the same Id as the button on the element, and then push it to the cart array. I then need to change the innertext of the "cartamnt" span so that based on how many items are added to the cart, text "0 cart" becomes "1 cart", etc..
//Arrays
var products = [{
Price: 20,
Name: "Football Helmet",
Description: "Titans football helmet",
Id: "Titan_a"
},
{
Price: 15,
Name: "Light Blue Shirt",
Description: "Titans light blue shirt",
Id: "Titan_b"
},
{
Price: 15,
Name: "White Shirt",
Description: "Titans white shirt",
Id: "Titan_c"
},
{
Price: 15,
Name: "Blue Shirt",
Description: "Titans blue shirt",
Id: "Titan_d"
},
{
Price: 25,
Name: "Hockey Stick",
Description: "Titans hockey stick",
Id: "Titan_d"
}
];
var cart = [];
//All the button variables
var addtocart = document.getElementsByClassName("add");
var camount = document.getElementById("cartamnt");
cartamnt.innerText = "0 cart"
addtocart.onclick = function(products, cart) {
for (var i = 0; i < products.length; i++) {
if (addtocart.Id == products.Id) {
cart.push(products.Id[i])
cartamnt.innerText = i++ + "cart"
}
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1 id="main_title">Titan Sports and Apparel LLC</h1>
<div class="main">
<div class="row">
<span href="checkout.html" id="cartamnt">0 cart</span>
<br />
</div>
<div class="row">
<div class="column">
<h1>Football helmet</h1>
<img id="img" src="img/Helmet_A.jpg">
<p>Price: $20</p>
<p>Official Titan Sportswear Helmet</p>
<button class="add" id="Titan_a">Add to cart</button>
<button id="Remove_a">Remove from cart</button>
</div>
<div class="column">
<h1>Light Blue Shirt</h1>
<img id="img" src="img/Shirt_A.jpg">
<p>Price: $15</p>
<p>Light blue cotton material Titans shirt</p>
<button class="add" id="Titan_b">Add to cart</button>
<button id="Remove_b">Remove from cart</button>
</div>
<div class="column">
<h1>White Shirt</h1>
<img id="img" src="img/Shirt_B.jpg">
<p>Price: $15</p>
<p>White cotton material Titans shirt</p>
<button class="add" id="Titan_c">Add to cart</button>
<button id="Remove_c">Remove from cart</button>
</div>
<div class="column">
<h1>Blue Shirt</h1>
<img id="img" src="img/Shirt_C.jpg">
<p>Price: $15</p>
<p>Blue cotton material Titans shirt</p>
<button class="add" id="Titan_d">Add to cart</button>
<button id="Remove_d">Remove from cart</button>
</div>
<div class="column">
<h1>Hockey Stick</h1>
<img id="img" src="img/Stick_A.png">
<p>Price: $25</p>
<p>Black Titans hockey stick</p>
<button class="add" id="Titan_e">Add to cart</button>
<button id="Remove_e">Remove from cart</button>
</div>
</div>
</div>
<a href="index.html">Homepage</a>
<footer>© Titan Sports and Apparel LLC | Email: TitanSportsApparel@gmail.com</footer>
<script src="js/shoppingCart.js"></script>
</body>
</html>