How to update and delete a cookie? - javascript

I need help to know how to update values and how to delete a cookie created from this code! I'm new to JavaScript so it's great if anyone can help me.
function getCookie(c_name) {
var i,x,y,ARRcookies = document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x = x.replace(/^\s+|\s+$/g,"");
if (x==c_name) {
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function check2Cookie() {
var username=getCookie("username");
if (username!=null && username!="") {
username= "0";
setCookie("username",username,1000);
}
else {
username=" ";
if (username!=null && username!="") {
username= "0";
setCookie("username",username,1000);
}
}
}
This is the code for cookie creation.
Code for creating is setCookie("username",username,1000);
Now how to update this cookie and delete this cookie.

The cookie API is kind of lame. Let me clarify...
You don't update cookies; you overwrite them:
document.cookie = "username=Arnold"; // Create 'username' cookie
document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck"
You also don't delete cookies; you expire them by setting the expires key to a time in the past (-1 works too).
Source: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

http://www.quirksmode.org/js/cookies.html
update would just be resetting it using createCookie
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);
}

http://www.quirksmode.org/js/cookies.html
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);
}

check this out A little framework: a complete cookies reader/writer with full Unicode support
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};

Related

cookies won't be deleted using js i am using the method below

function removeItem(key){
document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
console.log(key+"Deleted");
console.log(document.cookie);
}
You could use these code snippets from w3schools
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}

How to call a specific cookie is JS [duplicate]

This question already has answers here:
How do I create and read a value from cookie with javascript?
(23 answers)
Closed 8 years ago.
I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.
JavaScript code:
function cssLayout() {
document.getElementById("css").href = this.value;
}
function setCookie(){
var date = new Date("Februari 10, 2013");
var dateString = date.toGMTString();
var cookieString = "Css=document.getElementById("css").href" + dateString;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
HTML code:
<form>
Select your css layout:<br>
<select id="myList">
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
</form>
I find the following code to be much simpler than anything else:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(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) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Now, calling functions
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now.
These are much much better references than w3schools (the most awful web reference ever made):
How cookies work (quirksmode.org)
MDN document.cookie
Examples derived from these references:
// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
The Mozilla reference even has a nice cookie library you can use.
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.
Just use the setCookie and getCookie methods mentioned there.
So, the code will look something like:
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function cssSelected() {
var cssSelected = $('#myList')[0].value;
if (cssSelected !== "select") {
setCookie("selectedCSS", cssSelected, 3);
}
}
$(document).ready(function() {
$('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
<option value="select">--Select--</option>
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.
This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
Mozilla has some tests to prove this works in all cases.
There is an alternative snippet here:

How to set and read cookies JavaScript

I'm trying to make a popup that appears on my site the first time you visit it. But not any other time after that. So I'm trying to make it with cookies. But I'm having absolutely no luck.
I've tried following W3 school's tutorial but I haven't gotten anywhere.
What I'm doing is when the user closes the dialog, it sets a cookie. And I'm trying to make it so when you come back, the pop up doesn't appear because the cookie is set.
Here's my code.
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0)
return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var username=getCookie("username");
if (username!="") {
$('#firsttimee').css({display : 'none'});
} else {
if (username=="" || username==null) {
$('#firsttimee').css({display : 'block'});
}
}
}
function closepop(){
$('#firsttimee').css({display : 'none'});
var username = 'seen';
setCookie("username",username,365);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firsttimee">
<div id="firsttimetxt">
<center>
Click here.<br><br>
Done
</center>
</div>
</div>
Thanks in advance! :)
Here is a jsfidddle of my current work, for some reason when you click done the popup doesn't go away..
Use the cookie script from MDN, not W3Schools, looks like W3Schools is not setting the path.
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
and to set the cookie
docCookies.setItem("username",username,"Infinity");
and to get the cookie
docCookies.getItem("username") //returns the string
or
docCookies.has("username") //return boolean
I usually use below code for that:
function getCookie(cookieName) {
var i, x, y, cookiesArray = document.cookie.split(";");
for (i = 0; i < cookiesArray.length; i++) {
x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookieName) {
return unescape(y);
}
}
}
function checkCookie() {
hideCookieDiv();
var myCookie = getCookie("yourcookiename");
if (myCookie == null || myCookie != "true") {
showCookieDiv();
setCookie();
}
}
function hideCookieDiv() {
document.getElementById('YourDivId').style.display = "none";
}
function showCookieDiv() {
document.getElementById('YourDivId').style.display = "block";
}
function setCookie() {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 365);
document.cookie = "yourcookiename=true; expires=" + expirationDate.toUTCString();
}

Can't able to set expiry date in cookie using javascript?

I am using following function
function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
setCookie("userName","vimalraj.s",1);
It create cookies in a "session " not with a 24 hours expiry time .
how to fix this ?
UPDATE :
The above code works fine in my colleague's computer Firefox(27.0.1)
and it doesn't for me same Firefox version
I even tried "max-age" instead of "expires"
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent( cookie_value ) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
Nothing worked ...
Taken from quirksmode.org.
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);
}
Here is for one day
createCookie('ppkcookie','testcookie',1)
I suggest you to create a new cookie with same cookie name.
now you can set the new expire.
This will over ride the existing cookie since both are of same name.
Now the new cookie will have the new expires
old cookie
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
new cookie
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
I hope this will help

Set cookie and get cookie with JavaScript [duplicate]

This question already has answers here:
How do I create and read a value from cookie with javascript?
(23 answers)
Closed 8 years ago.
I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.
JavaScript code:
function cssLayout() {
document.getElementById("css").href = this.value;
}
function setCookie(){
var date = new Date("Februari 10, 2013");
var dateString = date.toGMTString();
var cookieString = "Css=document.getElementById("css").href" + dateString;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
HTML code:
<form>
Select your css layout:<br>
<select id="myList">
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
</form>
I find the following code to be much simpler than anything else:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(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) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Now, calling functions
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now.
These are much much better references than w3schools (the most awful web reference ever made):
How cookies work (quirksmode.org)
MDN document.cookie
Examples derived from these references:
// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
The Mozilla reference even has a nice cookie library you can use.
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.
Just use the setCookie and getCookie methods mentioned there.
So, the code will look something like:
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function cssSelected() {
var cssSelected = $('#myList')[0].value;
if (cssSelected !== "select") {
setCookie("selectedCSS", cssSelected, 3);
}
}
$(document).ready(function() {
$('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
<option value="select">--Select--</option>
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.
This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
Mozilla has some tests to prove this works in all cases.
There is an alternative snippet here:

Categories