Article

Saving an array to a cookie

https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js
Copy to clipboard

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

<script>
$(document).ready(function(){
  XT1
});
</script>
Copy to clipboard
Send to Live Demo

Live demo

<script>    
$(document).ready(function() {
  XT1
});
</script>
<script>
  
</script>
Copy to clipboard
Press the Run Demo button to execute the scripts above.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Your browser is too small

Resize your browser to be at least 769px wide.