How to use jquery.cookies.jsWithout jQueryIf 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) - jaaulde.utils.cookies.get('myCookie');
- returns value of myCookie if it is present, null if not
- jaaulde.utils.cookies.get(['myCookie', 'myOtherCookie']);
- returns array containing value of each requested cookie if it is present, null if not
- jaaulde.utils.cookies.get();
- returns array of all cookies from your site
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 ) - jaaulde.utils.cookies.filter( /^site/ );
- returns list of cookies whose names start with "site"
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) - jaaulde.utils.cookies.set('myCookie', 'myValue');
- sets cookie by the name of 'myCookie' to value of 'myValue' with default options
- jaaulde.utils.cookies.set('myCookie', 'myValue', {path: '/somedir'});
- sets cookie by the name of 'myCookie' to value of 'myValue' with path of '/somedir'
- See information on options object below
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) - jaaulde.utils.cookies.del('myCookie');
- deletes a cookie, 'myCookie', with default options
- jaaulde.utils.cookies.del('myCookie', {path: '/somedir'});
- deletes a cookie by the name of 'myCookie' which had been set with a path of '/somedir'
- jaaulde.utils.cookies.del(true);
- A cookie can only be deleted using the same options with which it was set
- See information on options object below
Test if browser is accepting cookies/**
* test - test whether the browser is accepting cookies
*
* @access public
* @return Boolean
*/
test = function() - jaaulde.utils.cookies.test();
- attempts to set a cookie and returns true or false upon success or failure
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) - jaaulde.utils.cookies.setOptions({path: '/somedir'});
- all cookies will be set or deleted with the path , '/somedir', unless it is explicitly provided in a passed options object
- See information on options object below
With jQueryIf jQuery is available, then all of the above methods are available to you under the jQuery.cookies (or $.cookies ) namespace: - $.cookies.get()
- $.cookies.filter()
- $.cookies.set()
- $.cookies.del()
- $.cookies.test()
- $.cookies.setOptions()
In addition, there are some jQuery function additions for helping automate some cookie tasks: - Set the value of a form field or the HTML of an element to a cookie named after the field's/element's name or id attribute
- $('#username').cookify();
- The value of the field, or HTML of the element, with id "username" is set to a cookie named after the name or id attribute of that field/element
- Fill a field's value, or an element's innerHTML with the value of a cookie
- $('#username').cookieFill();
- Set the value of the input, or HTML of the element, with id, 'username', to the value of a cookie by the same name
- Bind an input to the cookies library
- $('#username').cookieBind();
- Fills the field or element with id, 'username', with the cookie named the same and sets the field's/element's change event to fire cookify() to update the cookie when the input value changes
Options objectUsing 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: - domain
- STRING
- For which domain should the cookie be available
- path
- STRING
- For which path should the cookie be available
- hoursToLive
- NUMBER
- For how many hours should the cookie be valid? (Passing 0 means to delete the cookie at the end of the browser session--this is default. Negative values will delete the cookie, but you should use the del() method instead.)
- secure
- BOOL
- Should cookie be sent to server via HTTPS only?
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: - domain
- no value - will cause current domain of current page to be used
- path
- expiration
- no value--causes cookie to be deleted at end of browser session
- secure (send over HTTPS only)
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.
|
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!
How do you set the expiration date? How should that be formatted?
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
@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.
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.
@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
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
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); }@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.
@everyone How can i implements this code in a website? Is there are a sample of implementation code? Which vars i need to replace?
Thanks.
@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.
@auldridgej So, i put the js within <head> and change the hoursToLive and that is it? Got it! Thank you. ;-)
@tony.rodz5 well, yes, that's a start. Each option can be changed per cookie set(), or can be set globally via setOptions().
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.
Please open an issue and provide detailed information on which options you're attempting to override.
Thanks, Jim
@auldridgej Is there an option where jquery bind to cookie changes. tq
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.
@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!
Is there anyway to have the cookie expire on browser close and time based? which ever comes first?
@Peter.wolk no cookies do not have this functionality (AFAIK).
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?
@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.
@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 }@Peter.wolk good work and thanks for sharing!
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 {@michele.costabile issue #12 opened as an enhancement request
Wow! Thanks! Works like a charm, is so simple to use and is very well documented! Thanks for sharing!