How do I set and unset a cookie using jQuery, for example create a cookie named test
and set the value to 1
?
type: "GET", url: "http://example.com", cache: false, // NO setCookies option available, set cookie to document //setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl", crossDomain: true, dataType: 'json', xhrFields: { withCredentials: true }, success: function (data) { alert(data); });
If this is the case, then you can actually check if a user has enabled cookies or not using the following straightforward jQuery snippet: $(document). ready(function() { var dt = new Date(); dt. setSeconds(dt.
To delete a cookie with JQuery, set the value to null: $. cookie("name", null, { path: '/' });
js-cookie is a Jquery plugin which makes life easier to get and set the values for cookies.
Update April 2019
jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.
Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.
Basic examples:
// Set a cookie Cookies.set('name', 'value'); // Read the cookie Cookies.get('name') => // => 'value'
See the docs on github for details.
Before April 2019 (old)
See the plugin:
https://github.com/carhartl/jquery-cookie
You can then do:
$.cookie("test", 1);
To delete:
$.removeCookie("test");
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("test", 1, { expires : 10 });
If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.
To cover all the options:
$.cookie("test", 1, { expires : 10, // Expires in 10 days path : '/', // The value of the path attribute of the cookie // (Default: path of page that created the cookie). domain : 'jquery.com', // The value of the domain attribute of the cookie // (Default: domain of page that created the cookie). secure : true // If set to true the secure attribute of the cookie // will be set and the cookie transmission will // require a secure protocol (defaults to false). });
To read back the value of the cookie:
var cookieValue = $.cookie("test");
UPDATE (April 2015):
As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With