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?

Community
  • 1
  • 1
Amy
  • 247
  • 1
  • 7
  • 24

3 Answers3

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

Use document.cookie and yes, yes you can.

Naftali aka Neal
  • 138,754
  • 36
  • 231
  • 295
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

Anton Baksheiev
  • 2,151
  • 2
  • 12
  • 14