-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart.js
51 lines (42 loc) · 1.31 KB
/
cart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const addProduct = () =>{
const productField = document.getElementById('product-name');
const quantityField = document.getElementById('product-quantity');
const product = productField.value ;
const quantity = quantityField.value ;
productField.value = '';
quantityField.value = '';
console.log(product, quantity);
displayProduct(product, quantity);
savaProductToLocalStorage(product, quantity);
}
const displayProduct = (product, quantity) =>{
const ul = document.getElementById('product-container');
const li = document.createElement('li');
li.innerText = `${product}: ${quantity}`;
ul.appendChild(li);
}
const getStoredShoppingCart = () =>{
let cart = {};
const storedCart = localStorage.getItem('cart');
if(storedCart){
cart = JSON.parse(storedCart);
}
return cart;
}
const savaProductToLocalStorage = (product, quantity)=>{
const cart = getStoredShoppingCart();
cart[product] = quantity;
// console.log(cart);
const cartStringified = JSON.stringify(cart);
localStorage.setItem('cart', cartStringified);
}
const displayProductsFromLocalStorage = () =>{
const savedCart = getStoredShoppingCart();
console.log(savedCart);
for(const product in savedCart){
const quantity = savedCart[product];
console.log(product, quantity);
displayProduct(product, quantity);
}
}
displayProductsFromLocalStorage();