New to JS and trying to create a simple shopping cart using only vanilla JS. I have an item with details and an image that populates on a shopping cart page. I need to have a delete button that allows items to be removed individually from the shopping cart page. Below is the snippet of code I'm having trouble with:
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)}
And below is the full JS code in case it would be helpful for debugging. Any help is appreciated!:
//Global Variables
var quantity = "";
var glazes = "";
var img = "";
var addItem = "";
//Changes price when quantity is selected
function priceCounter(){
var price = document.getElementById("price-details");
price.innerHTML = document.getElementById("quantity").value;
}
function setImage(select){
var image = document.getElementsByName("image-swap")[0];
image.src = select.options[select.selectedIndex].value;
}
function items(title, quantity, glaze, price, img){
this.title = title;
this.quantity = quantity;
this.glaze = glaze;
this.price = price;
this.img = img;
}
//Add to Cart Functionality
function addToCart() {
var quantityCount = document.getElementById("quantityCount");
quantityCount.innerText = document.getElementById("quantity").value;
document.getElementById("quantityCount").style.visibility = "visible";
title = document.getElementsByClassName("productTitle");
quantity = document.getElementById("quantity").value;
glazing = document.getElementById("glazing").value;
price = document.getElementById("quantity").value;
img = "images/blackberry-bag.png"
addItem = new items(title, quantity, glazing, price, img);
window.localStorage.setItem(localStorageCount, JSON.stringify(addItem));
// localStorageCount += 1;
}
//creates array to hold bag items
var productArr = []
var productArr2 = []
class Product {
constructor(quantity, glaze) {
this.quantity = quantity
this.glaze = glaze
}
}
function addToCart() {
var quantity = document.getElementById('quantity').value
var glaze = document.getElementById('glaze').value
var bun = new Product(quantity, glaze)
productArr.push(bun)
updateCartNumber(productArr.length)
}
function goToCheckoutPage() {
alert("taking you to your cart")
localStorage.setItem('order', JSON.stringify(productArr))
window.location.replace("cart.html")
}
function checkoutPageLoaded() {
var loadedProductArr = localStorage.getItem('order')
var productArr2 = JSON.parse(loadedProductArr)
console.log(productArr2)
var cart = document.getElementById("cart")
for(var i = 0; i < productArr2.length; i++) {
var cinbun = productArr2[i]
var cinbunGlaze = cinbun.glaze
var cinbunQuantity = cinbun.quantity
cart.innerHTML += "<div class='cart-items'> Flavor: Pumpkin Spice Glaze: <img src="+ cinbunGlaze +"> Price: "+ cinbunQuantity +"</div>"
cart.innerHTML += "<span onclick= 'deleteProduct(" + i + ")'> Delete </span>"
}
}
function saveEdits() {
localStorage.setItem('order', JSON.stringify(productArr2))
}
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)
}
function updateCartNumber(num) {
var cartCount = document.getElementById('quantityCount')
cartCount.innerHTML = num
}
Related
I'm building an eCommerce website and I'm using local-storage for saving data to the shopping cart. However, I'm having some issues with it:
I can't add different items without losing the old ones (I guess the rows don't save); I noticed as soon as I click add to cart it overwrites the row with the new data. (I'm thinking it's probably that for loop that overwrites the data from i=1 again) as shown this is what I see https://imgur.com/buotLVe
the remove button doesn't seem to be working properly as well; it's driving me nuts!
My code might be all over the place so my apologies and any help are really appreciated.
selected-product.html
<div onclick="additem()" id="add-item-to-cart">
<h4>ADD TO CART</h4>
</div>
shopping-bag.html
<table>
<tr>
<th>IMAGE</th>
<th>ITEM</th>
<th>COLOR</th>
<th>PRICE</th>
<th>QUANTITY</th>
</tr>
<tr class="item-row"></tr>
<td id="cart-total-price-title">TOTAL:</td>
<td id="cart-total-price">$0.00</td>
</table>
cart.js
var itemCounter = 0;
var loopNum = 1;
function additem() {
itemCounter++;
loopNum++;
localStorage.setItem('item-count', itemCounter);
localStorage.setItem('item-loop', loopNum);
// alert(itemCounter);
addToCart();
}
function updateCartTotal() {
//
// Get the first table in the document.
var counter = localStorage.getItem('item-count');
var loop = localStorage.getItem('item-loop');
//alert('counter'+counter);
var table = document.getElementsByTagName('table')[0];
var count = 0;
var itemPrice = localStorage.getItem('saved-Price');
var totalPriceElement = document.getElementById('cart-total-price');
var cartRows = document.getElementsByClassName('item-row');
var cellOfItemColor = localStorage.getItem('saved-colorArray').split(',');
var cellOfitemQuantityInput = localStorage.getItem('saved-quantityArray').split(',');
var cellOfItemName = localStorage.getItem('saved-itemArray').split(',');
var imageArray = localStorage.getItem('saved-imageArray').split(',');
console.log(cellOfItemColor[0] + cellOfitemQuantityInput);
for (var i = 1; i <= counter; i++) {
var row = table.insertRow(i);
var cellOfItemImage = row.insertCell(0);
row.insertCell(1).innerText = cellOfItemName[i - 1];
row.insertCell(2).innerText = cellOfItemColor[i - 1];
row.insertCell(3).innerText = itemPrice;
row.insertCell(4).innerText = cellOfitemQuantityInput[i - 1];
var cellOfItemRemove = row.insertCell(5);
var image = document.createElement('img');
image.src = imageArray[i - 1];
image.setAttribute("width", "100");
image.setAttribute("height", "100");
cellOfItemImage.appendChild(image);
var removeRow = document.createElement("BUTTON");
removeRow.style.color = "black";
removeRow.style.padding = '10px';
removeRow.style.fontFamily = "Roboto, sans-serif, verdana, tahoma";
removeRow.style.letterSpacing = '3px';
removeRow.style.fontWeight = 'bold';
removeRow.innerText = "REMOVE";
cellOfItemRemove.append(removeRow);
localStorage.setItem('item-row', row);
removeRow.addEventListener('click', function () {
table.deleteRow(1);
localStorage.deleteItem('item-row');
});
var totalPrice = 0;
for (var i = 0; i < cartRows.length; i++) {
totalPrice = totalPrice + (itemPrice * 1 /*inputQuantityValue.value*/);
count++;
}
totalPrice = '$' + totalPrice.toFixed(2);
totalPriceElement.innerHTML = totalPrice;
console.log(count + ' Total: ' + totalPrice);
}
var colorArray = [];
var quantityArray = [];
var itemnameArray = [];
var itemimageArray = [];
function addToCart() {
var productQuantity = document.getElementById("qty").value;
var productColor = document.getElementById("clr-list").value;
var productModel = document.getElementById("model").value;
var currTitle = document.getElementById('product-title').innerHTML;
var productImageLocation = document.getElementById("product-img").src;
colorArray.push(productColor);
localStorage.setItem('saved-colorArray', colorArray);
quantityArray.push(productQuantity);
localStorage.setItem('saved-quantityArray', quantityArray);
itemnameArray.push(currTitle);
localStorage.setItem('saved-itemArray', itemnameArray);
itemimageArray.push(productImageLocation);
localStorage.setItem('saved-imageArray', itemimageArray);
if (productQuantity < 1) {
alert('Product quantity has to be at least one');
}
else {
alert('Item added! ' + currTitle + " Quantity: " + productQuantity + " Color: " + colorArray + " Model: " + productModel + 'img src : ' + productImageLocation);
updateCartTotal();
}
}
}
You are not reading the arrays as arrays from the local storage but rather than expecting a string of them separated by colons - even if it would work on some browsers, having any item containing "," in a property would break this.
You can store arrays as JSON, and in fact JSON supports more than this, you could consider storing an array with the items storing all their properties.
Also, you should really not trust the browser with the cart, especially handling prices and doing payments, as all the data can be easily manupulated.
I have a shopping Cart on my first page and all the items that have been selected I want it to be shown when user go to the other page.
I'm new in javascript that's why I couldn't figure out how to save those data in local storage. The main thing for me now is how to save the quantity that is being incremented.
NOTE: I'm using one script for two pages.
// this below function is executed when user on page ONE click on the button the quantity increase.
function addtocartbtnclicked(event) {
var button = event.target;
var shopitem = button.parentElement.parentElement;
var title = shopitem.querySelectorAll('h1')[0].innerText;
var price = shopitem.querySelectorAll('.card .price')[0].innerText;
var imgsrc = shopitem.querySelectorAll('.card .my-img')[0].src;
console.log(title, price, imgsrc);
additemtocard(title, price, imgsrc);
updatetotal();
quantityupdate();
}
// this function increase the quantity
function quantityupdate() {
var div = document.querySelectorAll('.each-cart-row');
var qtytotal = 0;
for (var i = 0; i < div.length; i++) {
var card = document.querySelectorAll('.add-to');
card = 1;
qtytotal = qtytotal + card;
}
console.log(qtytotal);
var count = document.querySelector('.totalqty').innerText = qtytotal;
}
var jsonStr = JSON.stringify(quantityupdate());
localStorage.setItem("cart", jsonStr);
// this function is for page TWO where another item will be added when the button is clicked
function addtocartbtnclickedpagetwo() {
var pageimg = document.querySelectorAll('.exzoom_img_ul img')[0].src;
var pagetitle = document.querySelector('#upper-area h3').innerText.slice(62);
var pageprice = document.querySelector('#last-list #product-total').innerText;
var pageqty = document.querySelector('#myform #input-number').value;
console.log(pageimg, pagetitle, pageprice, pageqty);
addtocartitempage(pageimg, pagetitle, pageprice, pageqty);
updatetotal();
var cartValue = document.querySelector('.totalqty')
cartValue = localStorage.getItem("cart");
var cartObj = JSON.parse(cartValue);
}
try to edit quantityupdate function so it actually saves qtytotal variable value to local storage:
function quantityupdate() {
var div = document.querySelectorAll('.each-cart-row');
var qtytotal = localStorage.getItem( "cart") || 0;
for (var i = 0; i < div.length; i++) {
var card = document.querySelectorAll('.add-to');
card = 1;
qtytotal = qtytotal + card;
}
localStorage.setItem( "cart", qtytotal);
var count = document.querySelector('.totalqty').innerText = qtytotal;
return
}
im writting a ShoppingCart class to add and remove items from the cart
code is meant to add and remove items from the shopping cart.
class ShoppingCart{
constructor(){
this.total = 0;
this.items = {};
}
addItems(itemName, quantity, price){
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
this.cost = this.quantity * this.price;
this.total += this.cost;
this.items['itemName'] = this.itemName;
this.items['quantity'] = this.quantity;
}
removeItems(itemName, quantity, price){
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
this.cost = this.quantity * this.price;
this.total -= this.cost;
delete this.items['itemName', 'quantity'];
}
}
Basically you need how to add and remove list items.
follow below approach and let me know if it works for you.
<ul id="todo"></ul>
<button onclick="addItemTodo('test')">Add</button>
js
function addItemTodo(text) {
list = document.getElementById("todo");
item = document.createElement('li');
item.innerText = text;
trash = document.createElement('button');
trash.classList.add('btn1');
trash.addEventListener("click", removeActivity);
icon_trash = document.createElement('i');
icon_trash.classList.add('fas', 'fa-trash-alt', 'fa-2x');
item.appendChild(trash);
trash.appendChild(icon_trash);
list.appendChild(item); }
function removeActivity() {
var listItems = document.getElementsByTagName("li");
for (var i = 0; i < listItems.length; i++) {
listItems[i].onclick = function() {
this.parentNode.removeChild(this);
}
}
}
Live demo
I am attempting to create a simple program for practice that has a Store constructor which takes in an inventoryList array, an InventoryItem constructor that creates an object of each item to be stored within the inventoryList array. I want to add a method to the InventoryItem list that will take a number and add it to each item within the list. Below is my code:
var Store = function(inventory){
this.inventory = inventory;
}
var InventoryItem = function(cost, color, size){
this.cost = cost;
this.color = color;
this.size = size;
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem( 18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
// add number of items to each item
InventoryItem.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].howMany = num;
}
}
}
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
I am running into an issue when I attempt add a number to an item within the list
example: dionStore.howMany(15)
this gives me the error: Uncaught TypeError: dionStore.howMany is not a function
Any help would be greatly appreciated preferably with a detailed explanation of why this doesn't work.
The problem is that the method howMany is defined for InventoryItem objects, but you try to call it to dionStore object which is a Store.
Can you please describe what you want to achieve?
EDIT1 :
Maybe add the howMany method to Store, like Lashane mentions, which will create a quantity property to each InvetoryItem in its array
Store.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].quantity = num;
}
}
}
EDIT2 :
In this case you will need a method in InventoryItem to set the quantity and another in Store to return the total quantity
Store.prototype.howMany = function(){
var totalQuantity = 0;
for(var i = 0; i < inventorylist.length; i++){
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
InventoryItem.prototype.addQuantity = function(quantity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += quantity;
} else {
this.quantity = quantity;
}
}
var Store = function(inventory) {
this.inventory = inventory;
}
Store.prototype.howMany = function() {
var totalQuantity = 0;
for (var i = 0; i < inventorylist.length; i++) {
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
var InventoryItem = function(cost, color, size) {
this.cost = cost;
this.color = color;
this.size = size;
}
InventoryItem.prototype.addQuantity = function(qunatity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += qunatity;
} else {
this.quantity = qunatity;
}
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem(18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
lamp.addQuantity(1);
throwPillow.addQuantity(2);
sconce.addQuantity(3);
candles.addQuantity(4);
curtains.addQuantity(5);
lamp.addQuantity(1);
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
document.getElementById('output').innerHTML = 'dionStore.howMany() = ' + dionStore.howMany();
<div id="output"></div>
Your prototype defines a function and does nothing. And it is on the wrong prototype. Are you looking for this?
Store.prototype.howMany = function(num){
for(var i = 0; i < this.inventory.length; i++){
this.inventory[i].howMany = num;
}
}
function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(inputbox.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
This will basically make a list when you hover over a certain string. The list will be based on the localstorage and make an inputbox for each point of that list.
The problem is the adding of eventlisteners. For some reason it always returns an empty value when the event is triggered of that inputbox.
function changeAmountProd(inputboxId) {
var products = JSON.parse(localStorage["products"]);
value = document.getElementById(inputboxId).value;
if(value < 1) {
return;
}
products[i].amount = value;
localStorage["products"] = JSON.stringify(products);
makeUL();
}
The problem is with the callback of your change event. You're referring to the changed element using the inputbox variable (that is available through the closure) but by the time your callback is invoked, inputbox will always point to the last generated element.
Try this instead:
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
See addEventListener
Try this:
function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}