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)
how to get single value by cookie in java script
I have written a small function (I could probably make this much more efficient, but I have used it for a long time) which should work for you:
function getCookieAttr(attribute) {
var attr = attribute + "="; // create an attribute string
var parts = document.cookie.split(';'); // split the cookie into parts
for(var i = 0; i <parts.length; i++) { // loop through the parts for each item
var item = parts[i];
while (item.charAt(0)==' ') { // account for spaces in the cookie
item = item.substring(1); // set the item
}
if (item.indexOf(attr) == 0) { // if the item matches the attribute
return item.substring(attr.length,item.length); // return the value
}
}
return "";
}
To use the function pass the attribute name:
document.cookie = "CookieName=grid";
console.log(getCookieAttr('CookieName'));
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 "";
}
Any simplest way to get cookie value in javascript
You could use a javascript library, e.g. jQuery in addition with a plugin: http://plugins.jquery.com/project/cookie
Demo page: http://stilbuero.de/jquery/cookie/
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;}
I can only make a cookie have one value in javascript
You can only set one cookie at a time. To assign multiple cookies, do separate assignments:
function makeCookie() {
document.cookie = "value=4";
document.cookie = "pi=3.14";
alert(document.cookie);
}
Within a cookie assignment, ;
is used to add optional attributes, e.g.
document.cookie = "value=4; max-age=900";
DEMO
How to set multiple key-value pairs to one cookie?
It does not make sense to store multiple key-value pairs into one cookie, because by definition a cookie represents one key-value pair.
I believe you don't understand well how document.cookie
works. It is not a standard JS string: when you set it, the cookie definition it contains is appended to the list of existing cookies. That is, you cannot set two cookies at the same time using this API.
You have two solutions:
Use a cookie for each key-value you want to store:
document.cookie = "myCookie=myValue";
document.cookie = "myOtherCookie=myOtherValue";Store a single cookie with a custom serialization of your complex data, for example JSON:
document.cookie = "myCookie=" + JSON.stringify({foo: 'bar', baz: 'poo'});
Related Topics
What Is an Exclamation Point in JavaScript
How to Fix Ajax to Always Fire When Checking Box
Vue.Js - How to Properly Watch for Nested Data
Rake Db:Create - Could Not Find a JavaScript Runtime
How to Get Objects Value If Its Name Contains Dots
What Do {Curly Braces} Around JavaScript Variable Name Mean
Non-Blocking Settimeout in JavaScript VS Sleep in Ruby
Retrieve Dom Target from Drag Callback When 'This' Is Not Available
Do I Need to Return After Early Resolve/Reject
Ios: Authentication Using Xmlhttprequest - Handling 401 Response
This' Different Between Repl and Script
How to Plug a JavaScript Engine with Ruby and Nokogiri
How to Pause Setinterval() Functions
Bitwise or in Ruby VS JavaScript
Why am I Getting Weird Result Using Parseint in Node.Js? (Different Result from Chrome Js Console)