Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over cookies using jquery (or just javascript)?

I am using the "Cookie Plugin" by Klaus Hartl to add or update cookies at $(document).ready. I have another event that is supposed to iterate all the cookies and do something with the value of each cookie. How can I iterate over the collection of cookies and get the id and value of each?

I'm thinking something like this:

$.cookie.each(function(id, value) { 
            alert('ID='+id+' VAL='+value); 
        });
like image 880
Byron Sommardahl Avatar asked Feb 10 '10 19:02

Byron Sommardahl


2 Answers

If you just want to look at the cookies it's not that hard without an extra plugin:

$.each(document.cookie.split(/; */), function()  {
  var splitCookie = this.split('=');
  // name is splitCookie[0], value is splitCookie[1]
});
like image 75
Pointy Avatar answered Oct 14 '22 17:10

Pointy


well it's rather easy in plain javascript:

var keyValuePairs = document.cookie.split(';');
for(var i = 0; i < keyValuePairs.length; i++) {
    var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
    var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
}
like image 25
David Hedlund Avatar answered Oct 14 '22 16:10

David Hedlund