简体   繁体   中英

how to make a shopping cart in javascript

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> 

This is basic shopping cart in which you type title in text box and price(it will be number only,character is not allowed) and by clicking on button item will be added to cart.

 var product=[]; function fun(){ var x={}; x.price=document.getElementById('price').value; x.title=document.getElementById('title').value; product.push(x); var iDiv = document.createElement('div'); iDiv.id = product.length; iDiv.className = 'block'; document.getElementsByTagName('body')[0].appendChild(iDiv); var para = document.createElement("span"); var node = document.createTextNode('Title: ' + x.title+' | '); para.appendChild(node); var element = document.getElementById(product.length); element.appendChild(para); para = document.createElement("span"); node = document.createTextNode('Price: '+ x.price); para.appendChild(node); element.appendChild(para); } 
 Title:<input id="title" type="text"> Price:<input id="price" type="number"> <button onClick="fun()">Add to Cart </button> <div> <p><b>Cart Info</b></p> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM