Reputation: 151
I have a mock webstore I'm making for a project and I can't seem to get my empty cart button working. The user clicks add or remove item to add or remove items from the cart, but my button to empty the cart isn't working.
<button type="button" onclick="removeAll()" style="color:black">Empty Cart</button>
I've tried removing each item individually with one button click but it only removed the first item in the array.
function removeItem(itemIndex) { //remove item from cart
cart.remove(itemIndex);
cart.display();
}
function removeAll(itemIndex) { //removes all items from cart
removeItem(0);
removeItem(1);
removeItem(2);
}
function Cart (holder, items) {
this.holder = holder;
this.items = items;
this.quantities = Array();
for (var i=0; i<items.length; i++)
this.quantities[i] = 0;
this.add = function (index) {
this.quantities[index]++;
}
this.remove = function (index) {
if (this.quantities[index] > 0)
this.quantities[index]--;
}
Any help would be appreciated, thanks
Upvotes: 2
Views: 90
Reputation: 1075527
Looking at that code, you want removeAll
to be:
function removeAll() { //removes all items from cart
var n;
for (n = 0; n < cart.quantities.length; ++n) {
cart.quantities[n] = 0;
}
cart.display();
}
...though it would probably make sense to put removeAll
on Cart.prototype
(adjusted accordingly).
Upvotes: 1
Reputation: 1446
Why not just reset the array?
function removeAll() {
this.items = [];
this.quantities = [];
}
Upvotes: 0