-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcart.js
More file actions
113 lines (84 loc) · 2.38 KB
/
cart.js
File metadata and controls
113 lines (84 loc) · 2.38 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Written with love by Anubhav Gupta
var cart = [];
window.onload = function loaded(){
if (localStorage.cart) {
cart = JSON.parse(localStorage.cart);
showCart();
}
if(! localStorage.cart)
document.getElementById("checkoutButton").style.visibility='hidden';
}
function addToCart(id, name, price) {
console.log("cart");
var price = price;
var name = name;
var id = id;
var qty = 1;
// update qty if product is already present
for (var i in cart) {
if (cart[i].Id == id) {
cart[i].Qty += 1;
saveCart();
showCart();
return;
}
}
// create JavaScript Object
var item = {
Id: id,
Product: name,
Price: price,
Qty: qty
};
cart.push(item);
console.log(cart);
saveCart();
showCart();
}
function subtractFromCart(i) {
// update qty if product is already present
cart[i].Qty += -1;
console.log(i);
if(cart[i].Qty==0)
deleteItem(i);
showCart();
saveCart();
return;
}
function incrementCart(i)
{
cart[i].Qty += 1;
showCart();
saveCart();
return;
}
function deleteItem(index) {
cart.splice(index, 1); // delete item at index
showCart();
saveCart();
}
function saveCart() {
if (window.localStorage) {
localStorage.cart = JSON.stringify(cart);
}
}
function showCart() {
if (cart.length == 0) {
document.getElementById("cart").style.visibility='hidden';
document.getElementById("checkoutButton").style.visibility='hidden';
return;
}
document.getElementById("cart").style.visibility='visible';
document.getElementById("checkoutButton").style.visibility='visible';
document.getElementById("cartBody").innerHTML="";
for (var i in cart) {
var item = cart[i];
document.getElementById("cartBody").innerHTML +=
"<tr><td>" + item.Product + "</td><td>" +
item.Price + "</td><td>" + item.Qty + "</td><td>" +
item.Qty * item.Price + "</td><td>" +
"<button onclick='deleteItem(" + i + ")'>Delete</button> </td><td>"+
"<button onclick='incrementCart(" + i + ")'>+</button> </td><td>"+
"<button onclick='subtractFromCart("+ i +")'>-</button></td></tr>";
}
}