My favorites | Sign in
Project Logo
                
Search
for
Updated Sep 19, 2009 by auldridgej
Labels: Featured
Documentation  
How to use jquery.cookies.js

How to use jquery.cookies.js

Without jQuery

If jQuery is not available in your page, the core cookies library is available to you under the jaaulde.utils namespace:

Get a cookie

/**
 * get - get one, several, or all cookies
 *
 * @access public
 * @paramater Mixed cookieName - String:name of single cookie; Array:list of multiple cookie names; Void (no param):if you want all cookies
 * @return Mixed - String:if single cookie requested and found; Null:if single cookie requested and not found; Object:hash of multiple or all cookies
 */
get = function(cookieName)

Get Filtered list of cookies

/**
 * filter - get array of cookies whose names match the provided RegExp
 *
 * @access public
 * @paramater Object RegExp - The regular expression to match against cookie names
 * @return Mixed - Object:hash of cookies whose names match the RegExp
 */
filter = function( cookieNameRegExp )

Set a cookie

/**
 * set - set or delete a cookie with desired options
 *
 * @access public
 * @paramater String cookieName - name of cookie to set
 * @paramater Mixed value - Null:if deleting, String:value to assign cookie if setting
 * @paramater Object options - optional list of cookie options to specify
 * @return void
 */
set = function(cookieName, value, options)

Delete a cookie

/**
 * del - delete a cookie (domain and path options must match those with which the cookie was set; this is really an alias for set() with parameters simplified for this use)
 *
 * @access public
 * @paramater MIxed cookieName - String name of cookie to delete, or Bool true to delete all
 * @paramater Object options - optional list of cookie options to specify ( path, domain )
 * @return void
 */
del = function(cookieName, options)

Test if browser is accepting cookies

/**
 * test - test whether the browser is accepting cookies
 *
 * @access public
 * @return Boolean
 */
test = function()

Set default options to use when none are specified

/**
 * setOptions - set default options for calls to cookie methods
 *
 * @access public
 * @param Object options - list of cookie options to specify
 * @return void
 */
setOptions = function(options)

With jQuery

If jQuery is available, then all of the above methods are available to you under the jQuery.cookies (or $.cookies ) namespace:

In addition, there are some jQuery function additions for helping automate some cookie tasks:

Options object

Using the options object, cookies can be set with several options such as the domain and or path for which the cookie should be available, expiration date for the cookie, and whether the cookie should be sent over HTTPS only.

The options object has four properties:

The structure of the object is as follows:

  var newOptions = {
    domain: '*.mydomain.com',
    path: '/somedir',
    hoursToLive: 24,
    secure: true
  }

You need only set those options which you desire to override.

The default options when not overridden are:

An options object can be passed with set(), del(), cookify(), and cookieBind() to override the defaults on a case by case basis. You can also pass an options object to setOptions() to override the defaults for all calls.

IMPORTANT NOTE: Cookies must be deleted using the same domain and path options with which they were set. Else the cookie will not delete. This is just how cookies work.


Comment by cmtonkinson, Dec 10, 2008

First off, thanks for this great jQuery plugin.

Second, thank you for avoiding puns when you mention that "This is just how cookies work." ;)

Cheers!

Comment by doug.bonneville, Jan 21, 2009

How do you set the expiration date? How should that be formatted?

Comment by xizhonghua, Jan 27, 2009

Thanks for this plugin.

But I got a problem. When I use chinese word in cookies. I got the cookie, but can't show the chinese word currectly. I use decodeURI to replace with the unescape to solve this problem.

xxfflower@qq.com

Comment by auldridgej, Jan 28, 2009

@all Sorry to have ignored the older comments and issues. I was not monitoring this page very closely as I assumed Google Code would email me when comments, issues, etc were left. I'll be watching more closely now.

@cmtonkinson - thank for the comments!

@doug.bonneville - I support expiration via the hoursToLive option. You just tell the library how many hours the cookie should be valid and it will produce the expiration time stamp

@xizhonghua - do you mind opening an issue for me on that? In that issue can you show me the code you used to fix the problem you're having? Thanks a lot!

I hope to have a patched version out soon with the small fixes for reported issues thus far.

Comment by digitalmatthew, Jan 31, 2009

Hi, first off, thank you for writing this plugin. It makes cookies much easier and faster to work with if you're using jQuery. I don't know why jQuery doesn't have this built in...MooTools? does. But, anyway, are there any issues with this plugin and jQuery 1.3.x ? I can't seem to get it to work.

Comment by auldridgej, Feb 02, 2009

@digitalmatthew I have done some limited testing with 1.3.1 and had no problems as of yet. I am working on releasing 2.0.1 of this library with a few fixes and hope to do full testing with jQ 1.3.1. I'd love it if you would open issues ( http://code.google.com/p/cookies/issues/list ) on the specific problems you're facing so that I know where to target some testing.

Thanks, Jim

Comment by marie.c.gale, Feb 02, 2009

Just wanted to drop a note and let you know that this documentation saved me hours of work! thank you for the clear descriptions and ease of use. Marie

Comment by docpommes, Feb 27, 2009

Great plugin! Thanks for sharing it with all of us! I made a slight modification to enable cookieBind() with <select> elements also:

In cookieFill() replace the nodeType check with this:

if (nodeType === 'input' || nodeType === 'textarea' || nodeType === 'select')
{
    $(this).val(value);
}
Comment by auldridgej, Feb 28, 2009

@docpommes that sounds great. I had written then method hastily and meant to get back to it to better support other things. I'll put in an Enhancement request on the Issues list and try to work this into 2.0.2.

Comment by tony.rodz5, May 05, 2009

@everyone How can i implements this code in a website? Is there are a sample of implementation code? Which vars i need to replace?

var newOptions = { domain: '.mydomain.com', path: '/somedir', hoursToLive: 24, secure: true }

Thanks.

Comment by auldridgej, May 05, 2009

@tony.rodz5 you do not need to replace any of the options unless you have a specific need in mind. The most common one replaced is hoursToLive as different cookies often need different expire times. As for how to implement, it depends on exactly what you're wanting to do.

Comment by tony.rodz5, May 05, 2009

@auldridgej So, i put the js within <head> and change the hoursToLive and that is it? Got it! Thank you. ;-)

Comment by auldridgej, May 05, 2009

@tony.rodz5 well, yes, that's a start. Each option can be changed per cookie set(), or can be set globally via setOptions().

Comment by imy...@zappos.com, May 16, 2009

I can't seem to set a cookie when using custom options. Works fine if I don't try to override the options. I'm using jQuery 1.3.2.

Comment by auldridgej, May 16, 2009

Please open an issue and provide detailed information on which options you're attempting to override.

Thanks, Jim

Comment by hudzaifah, May 27, 2009

@auldridgej Is there an option where jquery bind to cookie changes. tq

Comment by hammo...@yahoo.com, May 29, 2009

Couldn't get cookie.get to work and realized there is a limitation in IE with document.cookie if over 4096 bytes of cookies stored. Deleted some cookies and everything is great.

Comment by auldridgej, May 29, 2009

@hudzaifah - if you mean a way to have a cookie be stored under a different name than the ID/Name of the input to which you're binding it, I have not adding anything like that.

@hammo...@yahoo.com Thanks for the note!

Comment by Peter.wolk, Jun 11, 2009

Is there anyway to have the cookie expire on browser close and time based? which ever comes first?

Comment by auldridgej, Jun 11, 2009

@Peter.wolk no cookies do not have this functionality (AFAIK).

Comment by Peter.wolk, Jun 11, 2009

Thanks for the quick response! Another question, I can't seem to get a cookie that i know is on my machine. the page that's calling this code in on another domain but i don't believe that should matter since it should just be searching for the cookie on my machine.

var cookie_value = $.cookies.get('test_info', {domain: 'www.test.com', path : '/'});

I'm i doing this incorrectly?

Comment by auldridgej, Jun 11, 2009

@Peter.wolk when retrieving cookies, only the name of the desired cookie can be passed in. Cookie technology limits read to those cookies which have not expired, and were originally set for the current path/domain.

Comment by Peter.wolk, Jun 11, 2009

@my earlier comment: if anyone is interested in doing something when the session ends or time end, whichever comes first:

	$('#acpt').click(function () { 
		$.cookies.set('ses', 'full_acpt', {path : '/'});
		$.cookies.set('sxmns', 'full_acpt', {path : '/', hoursToLive: .1});
	});

	var cookie_value_ses = $.cookies.get('ses', {path : '/'});
	var cookie_value_sxmns = $.cookies.get('sxmns', {path : '/'});
	
	if(cookie_value_ses != "full_acpt")
	{
		//do something
	}else if(cookie_value_sxmns != "full_acpt"){
		//do something
	}
Comment by auldridgej, Jun 11, 2009

@Peter.wolk good work and thanks for sharing!

Comment by michele.costabile, Jun 18, 2009

Hello, this is the code I tried for supporting checkboxes and radio buttons.

Index: jquery.cookies.2.1.0.js
===================================================================
--- jquery.cookies.2.1.0.js	(revision 56)
+++ jquery.cookies.2.1.0.js	(working copy)
@@ -321,16 +321,18 @@
 								{
 									inputType = inputType.toLowerCase();
 								}
-								if( inputType !== 'radio' && inputType !== 'checkbox' )
+								resolvedValue = true;
+								if( inputType === 'radio' || inputType === 'checkbox' )
 								{
+								    value = $( this ).attr("checked");
+								} else {
 									value = $( this ).val();
-									resolvedValue = true;
 								}
 							}
 							
 							if( resolvedValue )
 							{
-								if( typeof value !== 'string' || value === '' )
+								if( value === '' || value === false)
 								{
 									value = null;
 								}
@@ -372,7 +374,13 @@
 								nodeName = this.nodeName.toLowerCase();
 								if( nodeName === 'input' || nodeName === 'textarea' || nodeName === 'select' )
 								{
-								    $( this ).val( value );
+								    inputType = $( this ).attr( 'type' );
+
+								    if ( inputType === 'checkbox' || inputType === 'radio' ) {
+								        $( this ).attr({checked: true});
+								    } else {
+								        $( this ).val( value );
+								    }
 								}
 								else
 								{
Comment by auldridgej, Jul 29, 2009

@michele.costabile issue #12 opened as an enhancement request

Comment by nando.losa, Oct 06, 2009

Wow! Thanks! Works like a charm, is so simple to use and is very well documented! Thanks for sharing!


Sign in to add a comment
Hosted by Google Code