How to get and set cookies in JavaScript
You can use some simple functions like setCookie()
and getCookie()
.
You can set a cookie using the call:
setCookie('myName','value', 3);
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;}
How do I create and read a value from cookie with javascript?
Here are functions you can use for creating and retrieving cookies.
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 = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
using javascript to get value of a cookie that was set in php
This is what I have been used in many projects, never had an issue.
Check the jsfiddle for usage.
Also, use your browser (like Chrome) to check all saved cookies make sure you have the cookie before you read it.
EXP: https://jsfiddle.net/1t4q9ejx/
/*-----------------------------------------------------
global function for Set/Get Cookie
------------------------------------------------------*/
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 + ";path=/";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
//set cookie
setCookie("selectedUnit", "10", 365);
//get cookie
let cookieUnits = getCookie("selectedUnit");
console.log('cookieUnits-->' + cookieUnits);
//list all cookies
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i - 1] + "\n";
}
return aString;
}
console.log(listCookies());
What is the best way to get and set a single cookie value using JavaScript
Stolen from http://www.quirksmode.org/js/cookies.html#script
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toUTCString();
}
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);
}
using it:
var oldCount = parseInt(readCookie('hitCount'), 10) || 0;
createCookie('hitCount', oldCount + 1, 7);
as pointed out in the comments, you should cast to an int since cookies are stored and returned as strings. Using foo++
or ++foo
will actually cast for you, but it's safer to know exactly what you're working with:
var x = "5"; // x = "5" (string)
x += 1; // x = "51" (string!)
x += 5; // x = "515" (string!)
++x; // x = 516 (number)
Set cookie with array() in jquery
Here's a way to do it based on some helper functions to make sure you are parsing and stringifying the cookie correctly.
getCookie and setCookie are from https://www.w3schools.com/js/js_cookies.asp
// This won't run due to security policies on this site, but you can run it in the dev tools and see.
function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.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 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 getCookieArray(cname) { var cookie = getCookie(cname); return cookie ? JSON.parse(cookie) : [];}
function pushToCookieArray(cname, cvalue, exdays) { var cookieArray = getCookieArray(cname); cookieArray.push(cvalue); setCookie(cname, JSON.stringify(cookieArray), exdays);}
function start(id) { pushToCookieArray('id', id, 7); console.log(getCookieArray('id'));}
start(5);start(6);start(8);
Related Topics
How to Change an Element'S Class With JavaScript
How to Change the Href Attribute For a Hyperlink Using Jquery
How to Get Value of Selected Radio Button
Maximum Size of a ≪Canvas≫ Element
How to Calculate the Number of Days Between Two Dates
Changing CSS Values With JavaScript
How to Loop Through Selected Elements With Document.Queryselectorall
How to Go to a Specific Element on Page
Capture Key Press (Or Keydown) Event on Div Element
Get the Position of a Div/Span Tag
JavaScript Function Doesn't Work When Link Is Clicked
How to Clear the Canvas For Redrawing
In What Situations Would Ajax Long/Short Polling Be Preferred Over Html5 Websockets
Reading File Contents on the Client-Side in JavaScript in Various Browsers
Insert HTML With React Variable Statements (Jsx)
Onchange Event Handler for Radio Button (Input Type="Radio") Doesn't Work as One Value
Es2015 Import Doesn't Work (Even At Top-Level) in Firefox
Removing All Script Tags from HTML With Js Regular Expression