79 lines
2.8 KiB
JavaScript
79 lines
2.8 KiB
JavaScript
$(document).ready(function () {
|
|
updateCartTotal();
|
|
document.getElementById("emptycart").addEventListener("click", emptyCart);
|
|
});
|
|
|
|
|
|
/* User Manually empty cart */
|
|
function emptyCart() {
|
|
//remove cart session storage object & refresh cart totals
|
|
if (sessionStorage.getItem('cart')) {
|
|
sessionStorage.removeItem('cart');
|
|
updateCartTotal();
|
|
updateCartCount();
|
|
//clear message and remove class style
|
|
}
|
|
}
|
|
|
|
function updateCartTotal() {
|
|
//init
|
|
var total = 0;
|
|
var price = 0;
|
|
var items = 0;
|
|
var prodCount = 0;
|
|
var productname = "";
|
|
var carttable = "";
|
|
if (sessionStorage.getItem('cart')) {
|
|
//get cart data & parse to array
|
|
var cart = JSON.parse(sessionStorage.getItem('cart'));
|
|
//get no of items in cart
|
|
items = cart.length;
|
|
//loop over cart array
|
|
for (var i = 0; i < items; i++) {
|
|
//convert each JSON product in array back into object
|
|
var x = JSON.parse(cart[i]);
|
|
//get property value of price;
|
|
productid = x.productid;
|
|
price = parseFloat(x.price);
|
|
productname = x.productname;
|
|
count = x.count;
|
|
totalperproduct = price * count;
|
|
totalperproduct = parseFloat(totalperproduct.toFixed(2));
|
|
//add price to total
|
|
carttable += "<tr><td>" + productid + "</td><td class='text-center'><button type='button' class='btn btn-danger removeproduct'>X</button></td><td>" + productname + "</td><td class='text-end'>" + price + "€</td><td class='text-end'>" + count + "</td><td class='text-end'>" + totalperproduct + "€</td></tr>";
|
|
total += totalperproduct;
|
|
total = parseFloat(total.toFixed(2));
|
|
prodCount += count;
|
|
}
|
|
|
|
}
|
|
//update total on website HTML
|
|
document.getElementById("total").innerHTML = total;
|
|
//insert saved products to cart table
|
|
document.getElementById("carttable").innerHTML = carttable;
|
|
//update items in cart on website HTML
|
|
document.getElementById("itemsquantity").innerHTML = prodCount;
|
|
|
|
var delbtns = document.getElementsByClassName("btn btn-danger removeproduct");
|
|
for (var i = 0; i < delbtns.length; i++) {
|
|
delbtns[i].addEventListener("click", function() { removeProductFromCart(this); });
|
|
}
|
|
}
|
|
|
|
function removeProductFromCart(elem) {
|
|
|
|
var productid = elem.parentNode.parentNode.children[0].innerText;
|
|
var cart = JSON.parse(sessionStorage.getItem('cart'));
|
|
var items = cart.length;
|
|
for (var i = 0; i < items; i++) {
|
|
var x = JSON.parse(cart[i]);
|
|
if (x.productid == productid) {
|
|
cart.splice(i, 1);
|
|
break;
|
|
}
|
|
}
|
|
var stringCart = JSON.stringify(cart);
|
|
sessionStorage.setItem('cart', stringCart);
|
|
updateCartTotal();
|
|
updateCartCount();
|
|
} |