how to store an array in jquery cookie?

I need to store an array in a jQuery cookie, any one help me please?


Solution 1:

Still not exactly sure what you need but i hope this will help. This is a sample that will allow you to access the items on any page, its just a sample! It uses the cookieName to identify it across the pages.

//This is not production quality, its just demo code.
var cookieList = function(cookieName) {
//When the cookie is saved the items will be a comma seperated string
//So we will split the cookie by comma to get the original array
var cookie = $.cookie(cookieName);
//Load the items or a new array if null.
var items = cookie ? cookie.split(/,/) : new Array();

//Return a object that we can use to access the array.
//while hiding direct access to the declared items array
//this is called closures see http://www.jibbering.com/faq/faq_notes/closures.html
return {
    "add": function(val) {
        //Add to the items.
        items.push(val);
        //Save the items to a cookie.
        //EDIT: Modified from linked answer by Nick see 
        //      http://stackoverflow.com/questions/3387251/how-to-store-array-in-jquery-cookie
        $.cookie(cookieName, items.join(','));
    },
    "remove": function (val) { 
        //EDIT: Thx to Assef and luke for remove.
        indx = items.indexOf(val); 
        if(indx!=-1) items.splice(indx, 1); 
        $.cookie(cookieName, items.join(','));        },
    "clear": function() {
        items = null;
        //clear the cookie.
        $.cookie(cookieName, null);
    },
    "items": function() {
        //Get all the items.
        return items;
    }
  }
}  

So on any page you can get the items like this.

var list = new cookieList("MyItems"); // all items in the array.

Adding items to the cookieList

list.add("foo"); 
//Note this value cannot have a comma "," as this will spilt into
//two seperate values when you declare the cookieList.

Getting all the items as an array

alert(list.items());

Clearing the items

list.clear();

You can add additional things like push and pop quite easily. Again hope this helps.

EDIT See bravos answer if you having issues with IE

Solution 2:

Download the jQuery cookie plugin here: http://plugins.jquery.com/project/Cookie

Setting a cookie with jQuery is as simple as this, where we are creating a cookie called "example" with a value of ["foo1", "foo2"]

$.cookie("example", ["foo1", "foo2"]);

Getting the cookie's value is also very easy with jQuery. The following would show the value of the "example" cookie in a dialog window

alert( $.cookie("example") );

Solution 3:

Check out my implementation (as a jquery plugin):

(function ($) {
    $.fn.extend({
        cookieList: function (cookieName) {
            var cookie = $.cookie(cookieName);

            var items = cookie ? eval("([" + cookie + "])") : [];

            return {
                add: function (val) {
                    var index = items.indexOf(val);

                    // Note: Add only unique values.
                    if (index == -1) {
                        items.push(val);
                        $.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
                    }
                },
                remove: function (val) {
                    var index = items.indexOf(val);

                    if (index != -1) {
                        items.splice(index, 1);
                        $.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
                     }
                },
                indexOf: function (val) {
                    return items.indexOf(val);
                },
                clear: function () {
                    items = null;
                    $.cookie(cookieName, null, { expires: 365, path: '/' });
                },
                items: function () {
                    return items;
                },
                length: function () {
                    return items.length;
                },
                join: function (separator) {
                    return items.join(separator);
                }
            };
        }
    });
})(jQuery);

Usage:

  var cookieList = $.fn.cookieList("cookieName");
  cookieList.add(1);
  cookieList.add(2);
  cookieList.remove(1);
  var index = cookieList.indexOf(2);
  var length = cookieList.length();

Solution 4:

I got error when I try to use almog.ori's script in IE 8

    //This is not production quality, its just demo code.
    var cookieList = function(cookieName) {
    //When the cookie is saved the items will be a comma seperated string
    //So we will split the cookie by comma to get the original array
    var cookie = $.cookie(cookieName);
    //Load the items or a new array if null.
    var items = cookie ? cookie.split(/,/) : new Array();

    //Return a object that we can use to access the array.
    //while hiding direct access to the declared items array
    //this is called closures see http://www.jibbering.com/faq/faq_notes/closures.html
    return {
        "add": function(val) {
            //Add to the items.
            items.push(val);
            //Save the items to a cookie.
            //EDIT: Modified from linked answer by Nick see 
            //      https://stackoverflow.com/questions/3387251/how-to-store-array-in-jquery-cookie
            $.cookie(cookieName, items.join(','));
        },
        "remove": function (val) { 
            //EDIT: Thx to Assef and luke for remove.
            indx = items.indexOf(val); 
            if(indx!=-1) items.splice(indx, 1); 
            $.cookie(cookieName, items.join(','));        },
        "clear": function() {
            items = null;
            //clear the cookie.
            $.cookie(cookieName, null);
        },
        "items": function() {
            //Get all the items.
            return items;
        }
      }

}  

after a few hours digging the error, i only realised that indexOf in

"remove": function (val) { 
                //EDIT: Thx to Assef and luke for remove.
                indx = items.indexOf(val); 
                if(indx!=-1) items.splice(indx, 1); 
                $.cookie(cookieName, items.join(','));        },

is not support in IE 8.

and so I add in another code base from here How to fix Array indexOf() in JavaScript for Internet Explorer browsers

it works,

"remove": function (val) {
    //EDIT: Thx to Assef and luke for remove.
    /** indexOf not support in IE, and I add the below code **/
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(obj, start) {
            for (var i = (start || 0), j = this.length; i < j; i++) {
                if (this[i] === obj) { return i; }
            }
            return -1;
        }
    }
    var indx = items.indexOf(val);
    if(indx!=-1) items.splice(indx, 1);
    //if(indx!=-1) alert('lol');
    $.cookie(cookieName, items.join(','));
},

just in case anyone found the script is not working in IE 8, this might help.