How to call a specific cookie is JS [duplicate] - javascript

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:

Related

Javascript - Delete Cookie by the beginning of the name [duplicate]

Is my function of creating a cookie correct? How do I delete the cookie at the beginning of my program? is there a simple coding?
function createCookie(name,value,days)
function setCookie(c_name,value,1) {
document.cookie = c_name + "=" +escape(value);
}
setCookie('cookie_name',mac);
function eraseCookie(c_name) {
createCookie(cookie_name,"",-1);
}
Try this:
function delete_cookie( name, path, domain ) {
if( get_cookie( name ) ) {
document.cookie = name + "=" +
((path) ? ";path="+path:"")+
((domain)?";domain="+domain:"") +
";expires=Thu, 01 Jan 1970 00:00:01 GMT";
}
}
You can define get_cookie() like this:
function get_cookie(name){
return document.cookie.split(';').some(c => {
return c.trim().startsWith(name + '=');
});
}
Here a good link on Quirksmode.
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+'=; Max-Age=-99999999;';
}
would this work?
function eraseCookie(name) {
document.cookie = name + '=; Max-Age=0'
}
I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.
Some of the other solutions might not work if you created the cookie manually.
Here's a quick way to delete a cookie:
document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;
If this doesn't work, try replacing location.host with location.hostname in the snippet above.
Here is an implementation of a delete cookie function with unicode support from Mozilla:
function removeItem(sKey, sPath, sDomain) {
document.cookie = encodeURIComponent(sKey) +
"=; expires=Thu, 01 Jan 1970 00:00:00 GMT" +
(sDomain ? "; domain=" + sDomain : "") +
(sPath ? "; path=" + sPath : "");
}
removeItem("cookieName");
If you use AngularJs, try $cookies.remove (underneath it uses a similar approach):
$cookies.remove('cookieName');
You can do this by setting the date of expiry to yesterday.
Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.
To delete a cookie I set it again with an empty value and expiring in 1 second.
In details, I always use one of the following flavours (I tend to prefer the second one):
1.
function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = key +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie(name, "", null , null , null, 1);
}
Usage:
setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");
2
function setCookie(params) {
var name = params.name,
value = params.value,
expireDays = params.days,
expireHours = params.hours,
expireMinutes = params.minutes,
expireSeconds = params.seconds;
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = name +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie({name: name, value: "", seconds: 1});
}
Usage:
setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");
For people who just want 1 line of code to delete a cookie:
If you created a cookie, for example in a web browser console with document.cookie = "test=hello"
You can delete it with:
document.cookie = "test=;expires=" + new Date(0).toUTCString()
Or if you prefer to write the UTC date directly:
document.cookie = "test=;expires=Thu, 01 Jan 1970 00:00:00 GMT"
If you are on a different path than the cookie (for example if you want to delete a cookie that is used on all paths), you can add path=/; after test=; and if you are on a different domain (for example when a cookie is set for all subdomains by using .example.com instead of www.example.com), you can add domain=.example.com; after test=;.
Update: instead of expires=..., using Max-Age=0 like in other answers works also (tested with Firefox).
I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:
if (document.cookie.length==0)
{
document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Cookies disabled');}
else
{
document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
else {alert('document.cookies.length = '+document.cookies.length);}
}
}
I use this on my websites that works on Chrome and Firefox.
function delete_cookie(name) { document.cookie = name +'=; Path=/; Domain=' + location.host + '; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=None; Secure' }
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) {
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
I used to generate the cookie from backend and redirect to frontend. The only way I got it working has been to set the expires date in the past in the backned and redirect back on frontend
We don't have the ability to delete cookies in JavaScript, so to delete it we need to create another cookie with an earlier date.
Set Cookie
let expires = null
const cookieName = 'userlogin'
const d = new Date();
d.setTime(d.getTime() + 2 * 24 * 60 * 60 * 1000);
document.cookie = cookieName + "=" + value+ ";" + expires + ";path=/";
Delete Cookie
let expires = null
const d = new Date();
d.setTime(d.getTime() - 2 * 24 * 60 * 60 * 1000);
expires = "expires=" + d.toUTCString();
document.cookie = 'userlogin' + "=" + value+ ";" + expires + ";path=/";

Remove Cookies In Jquery on logout button

Hi i am trying to make code for clear cookies in jquery onclick of logout button but didn't get solution
function logout()
{
document.cookie = 'Visit=; expires='+new Date(0).toUTCString() +'; path=/FinalVertozz/';
window.location='../login.html';
}
cookies details
Name: Visit
Content: 09850227123455130
Domain: localhost
Path: /FinalVertozz
Send for: Any kind of connection
Accessible to script: Yes
Created: Saturday, October 4, 2014 11:25:45 AM
Expires: When the browsing session ends
Can you use simple javascript. It's easy.
function ClearCookies()
{
var cookiesCollection = document.cookie.split(";");
for (var i = 0; i < cookiesCollection .length; i++)
{
var cookieName = cookiesCollection [i];
var pos= cookieName.indexOf("=");
var name = pos> -1 ? cookieName.substr(0, pos) : cookieName;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
From the reference of this question and answer from #Russ Cam
How do I set/unset cookie with jQuery?
Use this function to reuse
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(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 unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Hope it may help :)
This issue is the path. If you remove it things will work.
document.cookie = 'Visit=; expires='+new Date(0).toUTCString();
Also, you're not using any jQuery in the above example. The question may be better stated as "remove cookies in JavaScript on logout button".

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();
}

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:

How to update and delete a cookie?

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;
}
};

Categories