I'm having trouble making a shopping cart using Javascript for a project. I made buttons called Add to Cart, and I tried various ways so that when I click on the button, I add the product's name and price to the cart. I tried button onclick, but it isn't working. I tried addEventListener, but it shows the product information when I'm not clicking on the button for some reason. How can I make it so that when I click the button, it shows up the product information in the cart? Also, how do I need to create element div (the code I commented out below)?
I also don't know how I can show the product image on the shopping cart.
var shoppingCart = [];
function addToCart(title, price) {
var product = {};
product.title = title;
product.price = price;
shoppingCart.push(product);
displayShoppingCart();
}
function displayShoppingCart() {
var totalPrice = 0;
var displayTitle = document.getElementById("displayTitle");
var displayPrice = document.getElementById("displayPrice";
for (var product in shoppingCart) {
displayTitle.innerHTML = shoppingCart[product].title;
displayPrice.innerHTML = shoppingCart[product].price;
// title.createElement('div');
// div.className = "itemTitle";
// itemTitle = document.querySelectorAll(".itemTitle");
// itemTitle.innerHTML = shoppingCart[product].title;
}
}
var book1 = document.getElementById("book1");
book1.addEventListener("click", addToCart("Cracking the Coding Interview","$29.99"));
<button class="addcart" id="book1" onclick="addToCart("Cracking the Coding Interview", "$29.99")"> Add to Cart </button>
<div id="displayTitle"></div>
<div id="displayPrice"></div>