Create, read, and erase cookies with jQuery [duplicate]
Use JavaScript Cookie plugin
Set a cookie
Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3
Get a cookie
alert( Cookies.get("example") );
Delete the cookie
Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.
As I know, there is no direct support, but you can use plain-ol' javascript for that:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie
Google is my friend and it showed me this page:
- http://www.electrictoolbox.com/jquery-cookies/
- How do I set/unset cookie with jQuery?
- Can jQuery read/write cookies to a browser?