Saving an array to a cookie
We may need to store more than one piece of information to the user cookie to accomplish this we can use an array.
To set an array to a cookie we should write: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/cookies/ex3.js?actionable=true
Here the array stores the name, age and gender of a user into the cookie named user.
Because cookies can only be store text we use the function JSON.stringify() to convert our array to text.
Conversely we use the function JSON.parse() to convert our stored text to an array.
A more useful application of an array in a cookie is one that stores shopping cart items on an eCommerce website. https://raw.githubusercontent.com/finsweet/jqueryCourse/main/cookies/ex4.js?actionable=true In the above example we already have 3 items in our shopping cart but we can initialize it as empty using: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/cookies/ex5.js?actionable=true
$(document).ready(function(){
XT1
});
</script>
Live demo
$(document).ready(function() {
XT1
});
</script>