I am using the following code to set a cookie each time the same button is clicked, which has an increased numberical value each time it is clicked and saves the title of the product as the value (for example Name: 1, Value: Car):
var num=1;
function addCookie() {
var expString = "; expires=" + date.toGMTString();
var cookievalue=escape(document.querySelector("[name=addpart]").value) + ";";
document.cookie=num + "=" + cookievalue + expString + "; path=/";
num++;
}
It works nicely on my page, setting a new cookie name each time it is clicked as '1', then '2', then '3' and so on, but obviously that just leaves me with:
However, when I go to another page and click the button again, it overwrites the cookie with the name 1 and starts the process again.
I would like to know how I can continue the name count for this button across pages? So that the user can browse the products and click the button which essentially produces a list that can be called later:
I understand it would be easier to create new buttons for each page, but I use a template system on my wesbite and we have thousdands of product pages so that's not a viable option for me.
Is pretty easy storing an array of objects, is better in my opinion using localStorage instead of cookie.
//example of first structure
localStorage.setItem("visits", JSON.stringify({"1":[],"2":[],"3":[]}));
//getting the item
var visits = JSON.parse(localStorage.getItem("visits"));
//different visits
visits["1"].push("Car");
visits["1"].push("Bike");
visits["1"].push("Something");
visits["2"].push("Bike");
visits["2"].push("Bike");
visits["2"].push("Something");
visits["3"].push("Something");
visits["3"].push("Something");
visits["3"].push("Something");
//setting the item
localStorage.setItem("visits", JSON.stringify(visits));
console.log(visits)
Example here https://jsfiddle.net/0kp9s2bv/