Set Cookie and Get Cookie With JavaScript

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



Leave a reply



Submit