views:

155

answers:

3

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); 
        });
A: 

with that, you can get cookie with:

$.cookie(COOKIE_NAME)
Reigel
Indeed, but I need to iterate over all cookies. I don't know their names or ids at that point in the code.
Byron Sommardahl
A: 

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);
}
David Hedlund
watch out for the leading spaces! You should split with the regex /; */ instead of just the string ';'.
Pointy
quite right, thank for pointing it out, pointy
David Hedlund
+2  A: 

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

$.each(document.cookie.split(/; */), function(cookieString)  {
  var splitCookie = cookieString.split('=');
  // name is splitCookie[0], value is splitCookie[1]
});
Pointy
Excellent solution. Split with regex is much better.
Byron Sommardahl
All correct except the function definition in the first line. Change function(cookieString) to function(index, cookieString) and you've got it!
Byron Sommardahl
oh right - sorry! Also I think jQuery binds "this" to each element, so you could also leave it off and just split "this" inside the function.
Pointy
actually, you *should* split `this` rather than `cookieString`, for the value of `cookieString` will be the zero-based index of the iteration.
David Hedlund