I need some help with my Shopping Cart. I’m using cookie to create it and my code is working, but there is one thing missing.Right now when I add a couch in my cookie, my cookie looks like this :
[{"colors":["Black/Yellow","Black/Red"],"_id":"415b7cacb65d43b2b5c1ff70f3393ad1","name":"Kanap Cyllène","price":4499,"imageUrl":"http://localhost:3000/images/kanap02.jpeg","description":"Morbi nec erat aliquam, sagittis urna non, laoreet justo. Etiam sit amet interdum diam, at accumsan lectus.","altTxt":"Photo d'un canapé jaune et noir, quattre places"}]
And my console.log gives me this :
[{…}]
0: {colors: Array(2), _id: '415b7cacb65d43b2b5c1ff70f3393ad1', name: 'Kanap Cyllène', price: 4499, imageUrl: 'http://localhost:3000/images/kanap02.jpeg', …}
The user is able to add the couch he selected in the cookie but he has several color options and I want my cookie to take the value selected by the user because for the moment my cookie is an array with the selected couch and in this array there is the array of the several color choices. I tried to simply add the value in my array but it doesn’t work. I tried this :
let couchColor = document.getElementById("colors").value
if(cart === null) {
cart = [couch + couchColor]
console.log(cart)
}
But with this my cookie doesn’t understand couch anymore and looks like this :
["[object Object]Black/Yellow"]
Can someone help me please ? I want the array of color to be replaced by the value selected by the user. Here is my code :
.then((couch) => {
let newImage = document.createElement("img");
newImage.src = couch.imageUrl;
newImage.alt = couch.altTxt;
image[0].appendChild(newImage);
title.innerHTML = couch.name;
price.innerText = couch.price;
description.innerText = couch.description;
// Choix couleurs
for (choice in couch.colors) {
colors.options[colors.options.length] = new Option(
couch.colors[choice], couch.colors[choice]
);
}
// Ajouter produit au panier https://stackoverflow.com/questions/10730362/get-cookie-by-name
addButton.onclick = ('click', function () {
let cart = getCookieByName("cart")
let couchColor = document.getElementById("colors").value
if(cart === null) {
cart = [couch + couchColor]
console.log(cart)
} else {
cart = JSON.parse(cart)
cart.push(couch)
}
document.cookie = "cart=" + JSON.stringify(cart)+";"
})
})
}
function getCookieByName(name)
{
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) {
return match[2];
}
else{
return null
}
}