Manage (Add, Edit, & Delete) cookies in jQuery

Monday, June 27, 2011

Setting and deleting cookies with jQuery is really easy (especially in
comparison to regular JavaScript) but this feature is not included in
the jQuery core. For this we need a plug-in. This post shows how to set
and get the value of cookies with jQuery.

First download the jQuery cookie plugin for here:

Set a cookie

Setting a cookie with jQuery is as simple as this, here
we are creating a cookie called “example” with a value “demo”:

$.cookie("example", "demo");

This is a session cookie and will be destroy when user close his/her
browser. To make the same cookie for suppose 7 days. We can do it like

$.cookie("example", "demo", { expires: 7 });

The above example will create the cookie at the root level. If you
wanted to make it apply only to e.g. “/admin” and make it for 7 days you
can do it like this:

$.cookie("example", "demo", { path: '/admin', expires: 7 });

Get the cookie’s value

Getting the cookie’s value is also very easy
in jQuery. The following would alert the value of “example” cookie:

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

Delete the cookie

And finally, to delete a cookie set its value to
Note:Setting it to e.g. an empty string doesn’t remove it;
it just clears the value.

$.cookie("example", null);

This entry was tagged jQuery

comments powered by Disqus

© 2009-2013 All rights reserved. Powered by Pyramid

go to Top