1

Possible Duplicate:
How to set/unset cookie with jQuery?

How would I go about creating a cookie using jquery to save a number of form fields on a website, also is it possible to save a cookie without using a save function, but instead when the each textfield, checkbox etc. is interacted with?

1

3 Answers 3

2

jQuery makes cookies very straightforward and easy to use.

If you want to set a cookie, simply add this line of jQuery code:

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

This cookie is set for the current path level and will be destroyed when the user closes their browser. If you want to make a cookie last longer, for example 10 days, do this:

$.cookie("example", "foo", { expires: 10 });


To make a cookie available for all paths on your domain, set the path to everything:

$.cookie("example", "foo", { path: '/' });

Or, if you want to isolate the cookie to a single path or directory, use this instead:

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


To get the value of the cookie, you could show it's value inside an alert box, like so:

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

Or, put it inside a variable for later use:

var cookievalue = $.cookie('example');


Finally, to delete a cookie, simply set the value to null. Note that simply setting an empty string will not remove the cookie, just clear its value.

$.cookie("example", null);
1
1

Use document.cookie and yes, yes you can.

1
  • I think it is document.cookie only
    – james_bond
    Nov 5, 2012 at 19:52
0

Set a cookie

$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
$.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

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

Delete the cookie

$.cookie("example", null);

Plugin jquery cookie

Not the answer you're looking for? Browse other questions tagged or ask your own question.