Implementazione carrello

This commit is contained in:
2026-04-01 13:38:49 +02:00
parent a953769a1b
commit f9bff1f235
5 changed files with 204 additions and 2 deletions
+58
View File
@@ -0,0 +1,58 @@
function addToCart(productId, productName, price) {
// Leggi il carrello dal cookie
let cart = [];
const cookieValue = document.cookie.split('; ').find(row => row.startsWith('cart='));
if (cookieValue) {
cart = JSON.parse(decodeURIComponent(cookieValue.split('=')[1]));
}
// Controlla se il prodotto è già nel carrello
const existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
cart.push({
id: productId,
name: productName,
price: price,
quantity: 1
});
}
// Salva il carrello nel cookie (scadenza 7 giorni)
const date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = "cart=" + encodeURIComponent(JSON.stringify(cart)) + "; " + expires + "; path=/";
alert('Prodotto aggiunto al carrello!');
}
function removeFromCart(index) {
let cart = [];
const cookieValue = document.cookie.split('; ').find(row => row.startsWith('cart='));
if (cookieValue) {
cart = JSON.parse(decodeURIComponent(cookieValue.split('=')[1]));
}
cart.splice(index, 1);
const date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
if (cart.length > 0) {
document.cookie = "cart=" + encodeURIComponent(JSON.stringify(cart)) + "; " + expires + "; path=/";
} else {
document.cookie = "cart=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
}
location.reload();
}
function clearCart() {
if (confirm('Sei sicuro di voler svuotare il carrello?')) {
document.cookie = "cart=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
location.reload();
}
}