# Example Cookie full  (ok)

```
// functions cookie
function create_cookie(name, value, days) { 
    if (days) { 
        var date = new Date(); 
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); 
        var expires = "; expires=" + date.toGMTString(); 
        document.cookie = name + "=" + value + expires + "; path=/"; 
    } else { 
        document.cookie = name + "=" + value; 
    } 
}

function get_cookie(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 remove_cookie(name) {
    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
}
```

```
// Xử lý front end
var client_location = 'hn';
create_cookie( 'client_location', client_location, 365 );
var client_location = get_cookie('client_location');
console.log(client_location);
// Kết qủa: hn
```

```
// Back end
<?php  
     if (isset($_COOKIE['client_location'])) {
		define ( 'LOCATION', $_COOKIE['client_location'] );
	} else {
		define ( 'LOCATION', 'cg' );
	}
?>
```

{% embed url="<https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript>" %}

## [Set cookie and get cookie with JavaScript \[duplicate\]](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript)

[Ask Question](https://stackoverflow.com/questions/ask)Asked 9 years, 5 months agoModified [1 year, 11 months ago](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript?lastactivity)Viewed 1.4m times678197**This question already has answers here**:[How do I create and read a value from cookie with javascript?](https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie-with-javascript) (24 answers)Closed 7 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:

```javascript
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:

```xml
<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>
```

[javascript](https://stackoverflow.com/questions/tagged/javascript)[html](https://stackoverflow.com/questions/tagged/html)[css](https://stackoverflow.com/questions/tagged/css)[cookies](https://stackoverflow.com/questions/tagged/cookies)[Share](https://stackoverflow.com/q/14573223)[Improve this question](https://stackoverflow.com/posts/14573223/edit)Follow[edited Mar 1, 2018 at 21:53](https://stackoverflow.com/posts/14573223/revisions)[![user avatar](https://www.gravatar.com/avatar/b55204190e15de8b82417156eb30b45e?s=64\&d=identicon\&r=PG\&f=1)](https://stackoverflow.com/users/9025498/aaron-martin)[Aaron Martin](https://stackoverflow.com/users/9025498/aaron-martin)12811 silver badge1313 bronze badgesasked Jan 28, 2013 at 23:34[![user avatar](https://www.gravatar.com/avatar/6ca0a9001ea184d5b37e4052f4cbdbd4?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/1420480/drwooolie)[DrWooolie](https://stackoverflow.com/users/1420480/drwooolie)7,05977 gold badges1919 silver badges1919 bronze badges

* 9`kaka = "Css=document.getElementById("css").href" + kakdatum;` is a syntax error. – [Bergi](https://stackoverflow.com/users/1048572/bergi) [Jan 28, 2013 at 23:37](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment20337396_14573223)
* what i wonder is how to set cookie based on a choice. If i choose a specific css file, then i want that file to be saved and activated the next time i open the html file – [DrWooolie](https://stackoverflow.com/users/1420480/drwooolie) [Jan 28, 2013 at 23:41](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment20337465_14573223)
* @DrWooolie How about marking an answer correct so visitors to this question will find the best answer? The top answer clearly isn't the best. – [JohnAllen](https://stackoverflow.com/users/464273/johnallen) [May 12, 2014 at 20:00](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment36259849_14573223)
* Now (2017), some use cases make investigating the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API), as opposed to cookies, worthwile. – [MattBianco](https://stackoverflow.com/users/385571/mattbianco) [Aug 3, 2017 at 9:02](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment77919526_14573223)
* A concise but fully featured modern approach to get/set cookies over at the duplicate question: [stackoverflow.com/a/48706852/87520](https://stackoverflow.com/a/48706852/87520) – [SamGoody](https://stackoverflow.com/users/87520/samgoody) [Feb 19, 2018 at 9:32](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment84729163_14573223)&#x20;

[Show **1** more comment](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript)

### 4 Answers

Sorted by:Trending sort available                                               Highest score (default)                                                                   Trending (recent votes count more)                                                                   Date modified (newest first)                                                                   Date created (oldest first)                              1053

I find the following code to be much simpler than anything else:

```javascript
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**

```javascript
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.

[Share](https://stackoverflow.com/a/24103596)[Improve this answer](https://stackoverflow.com/posts/24103596/edit)Follow[edited Jul 12, 2020 at 14:27](https://stackoverflow.com/posts/24103596/revisions)[![user avatar](https://i.stack.imgur.com/00Kof.jpg?s=64\&g=1)](https://stackoverflow.com/users/5883282/fakhruddin-ujjainwala)[Fakhruddin Ujjainwala](https://stackoverflow.com/users/5883282/fakhruddin-ujjainwala)2,4631616 silver badges2626 bronze badgesanswered Jun 8, 2014 at 6:28[![user avatar](https://www.gravatar.com/avatar/5955c683278cbb3d452db47a46b0aa16?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/895724/mandeep-janjua)[Mandeep Janjua](https://stackoverflow.com/users/895724/mandeep-janjua)14.4k44 gold badges2727 silver badges2424 bronze badges

* 7`toGMTString()` is deprecated - just FYI. [Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString) – [Keith W.](https://stackoverflow.com/users/2411988/keith-w) [Nov 20, 2015 at 19:48](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment55434985_24103596)&#x20;
* 14This won't work if your cookie contains a semicolon. – [lucaswxp](https://stackoverflow.com/users/786418/lucaswxp) [Jan 11, 2016 at 21:31](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment57209101_24103596)
* 7Why so complex? Use `date.setDate(date.getDate() + days);` instead – [dude](https://stackoverflow.com/users/3894981/dude) [Mar 8, 2018 at 15:22](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment85358408_24103596)
* 5The **eraseCookie** function didn't work for me (FireFox Developer Edition 66.0b4). Instead, I had to use the code from B T's answer: `document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'`. – [ban-geoengineering](https://stackoverflow.com/users/1617737/ban-geoengineering) [Feb 1, 2019 at 20:28](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment95780132_24103596)&#x20;
* 4Nice answer. While using semicolon(;) in cookie value I have got problem. So I refined some lines. Please update in your answer. From **function setCookie(name,value,days)** `document.cookie = name + "=" + (encodeURIComponent(value) || "") + expires + "; path=/";` From **function getCookie(name)** `if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));` Use `encodeURIComponent(), decodeURIComponent()` in retutn statement; – [KarthikeyanMlp](https://stackoverflow.com/users/2736861/karthikeyanmlp) [Mar 1, 2019 at 13:36](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment96654341_24103596)&#x20;

[Show **19** more comments](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript)424

These are much *much* better references than w3schools (the most awful web reference ever made):

* [How cookies work (quirksmode.org)](http://www.quirksmode.org/js/cookies.html)
* [MDN document.cookie](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie)

Examples derived from these references:

```javascript
// 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.

[Share](https://stackoverflow.com/a/17521905)[Improve this answer](https://stackoverflow.com/posts/17521905/edit)Follow[edited Aug 3, 2020 at 11:35](https://stackoverflow.com/posts/17521905/revisions)[![user avatar](https://i.stack.imgur.com/ef14A.png?s=64\&g=1)](https://stackoverflow.com/users/2202537/lin)[lin](https://stackoverflow.com/users/2202537/lin)17.5k44 gold badges5555 silver badges8282 bronze badgesanswered Jul 8, 2013 at 8:18[![user avatar](https://www.gravatar.com/avatar/da9a54a87c0541814289cc1fb434de11?s=64\&d=identicon\&r=PG\&f=1)](https://stackoverflow.com/users/122422/b-t)[B T](https://stackoverflow.com/users/122422/b-t)53k3434 gold badges176176 silver badges200200 bronze badges

* 28The expires variable is obsolete although still supported by browsers. Use max-age instead! – [tyler](https://stackoverflow.com/users/13257901/tyler) [Jul 25, 2013 at 1:34](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment26054181_17521905)
* 61It looks like IE8 and below do not support `max-age`, so `expires` is the safer choice. [blogs.msdn.com/b/ieinternals/archive/2009/08/20/…](http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx) – [thaddeusmt](https://stackoverflow.com/users/164439/thaddeusmt) [Oct 8, 2013 at 16:29](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment28501217_17521905)
* 5There's also a `domain` param you can set on cookies which is useful if you want to use a cookie across different sub domains on your site. – [Alex W](https://stackoverflow.com/users/1399491/alex-w) [Oct 25, 2013 at 20:26](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment29090740_17521905)
* 2Dont work on Chrome. See here why: [stackoverflow.com/questions/26349052/…](https://stackoverflow.com/questions/26349052/why-would-setting-document-cookie-not-work-in-chrome) – [Peter](https://stackoverflow.com/users/3957352/peter) [Apr 6, 2018 at 14:10](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment86401968_17521905)
* 2Note that the MDN reference page mentions nothing about `expires` being deprecated/obsolete. That's because it can, on occasion, serve a purpose not covered by `max-age`. The value of `max-age` must be a numerical value interpreted as an amount of seconds, while the `expires` value can be set to the special value `Session` which is **not the same as `max-age=0;`**. – [ocket8888](https://stackoverflow.com/users/3777314/ocket8888) [May 4, 2018 at 17:57](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment87378477_17521905)

[Show **2** more comments](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript)38

Check [JavaScript Cookies on W3Schools.com](http://www.w3schools.com/js/js_cookies.asp) for setting and getting cookie values via JS.

Just use the setCookie and getCookie methods mentioned there.

So, the code will look something like:

```xml
<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>
```

[Share](https://stackoverflow.com/a/14573665)[Improve this answer](https://stackoverflow.com/posts/14573665/edit)Follow[edited Sep 24, 2016 at 9:41](https://stackoverflow.com/posts/14573665/revisions)[![user avatar](https://i.stack.imgur.com/0fqUn.jpg?s=64\&g=1)](https://stackoverflow.com/users/1372621/stacked)[Stacked](https://stackoverflow.com/users/1372621/stacked)6,32466 gold badges5555 silver badges7373 bronze badgesanswered Jan 29, 2013 at 0:20[![user avatar](https://www.gravatar.com/avatar/6a2eb324539366fd247497007ed56343?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/1937785/munish-poonia)[Munish Poonia](https://stackoverflow.com/users/1937785/munish-poonia)77844 silver badges33 bronze badges

* 13\@BT could you elaborate on what about the above code is out of date and misinformed? – [Justin](https://stackoverflow.com/users/922522/justin) [Dec 10, 2013 at 19:08](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment30647939_14573665)
* 14\@BT, I've yet to see a reference on w3schools that is out of date or contains incorrect information. – [Cypher](https://stackoverflow.com/users/218125/cypher) [Jan 8, 2014 at 1:14](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment31532194_14573665)
* 17-1 for w3schools – [ohcibi](https://stackoverflow.com/users/1250436/ohcibi) [Jan 13, 2014 at 12:09](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment31724469_14573665)
* 10I just checked our analytics, and 10% of our IE users still use IE8 or lower. So using 'max-age' is a pretty bad idea. – [CpnCrunch](https://stackoverflow.com/users/1192732/cpncrunch) [Nov 12, 2014 at 19:32](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment42343459_14573665)
* 18Stupidness!! +1 for the working example, I don't actually see a problem with w3schools, – [amd](https://stackoverflow.com/users/1104402/amd) [Mar 27, 2015 at 10:03](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment46791043_14573665)

[Show **4** more comments](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript)36

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](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) and probably is trustable. This is UTF-safe object for work with cookies:

```javascript
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](http://mdn.beonex.com/en/DOM/document.cookie.html):

[Share](https://stackoverflow.com/a/24035852)[Improve this answer](https://stackoverflow.com/posts/24035852/edit)Follow[edited Jun 4, 2014 at 14:20](https://stackoverflow.com/posts/24035852/revisions)[![user avatar](https://www.gravatar.com/avatar/a007be5a61f6aa8f3e85ae2fc18dd66e?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/-1/community)[Community](https://stackoverflow.com/users/-1/community)Bot111 silver badgeanswered Jun 4, 2014 at 11:09[![user avatar](https://www.gravatar.com/avatar/83a4742ec21ef2fff092cf009326e126?s=64\&d=identicon\&r=PG)](https://stackoverflow.com/users/139361/dan)[Dan](https://stackoverflow.com/users/139361/dan)52.7k3939 gold badges111111 silver badges150150 bronze badges

* 6Just a word of warning @SandipPingle, the code provided in this answer is actually GPL licensed. – [jahu](https://stackoverflow.com/users/2123652/jahu) [Aug 9, 2014 at 16:03](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment39282746_24035852)
* @MarcinHabuszewski thanks for pointing out. How can I use this code then(my app is not GPL licensed)? – [Sandip Pingle](https://stackoverflow.com/users/1254813/sandip-pingle) [Aug 11, 2014 at 5:55](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment39313882_24035852)
* 8\@SandipPingle That's the "charm" of GPL, you can't (unless you turn your app GPL). This code is somewhat similar to a generic solution to the problem, so it begs for a question: can generic code actually be licensed (or is such license valid in case of generic code)? Try using different (non-GPLed) code to solve your problem. – [jahu](https://stackoverflow.com/users/2123652/jahu) [Aug 11, 2014 at 11:38](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment39324217_24035852)
* 18GPL or not, I prefer code I can **read**. – [Cypher](https://stackoverflow.com/users/218125/cypher) [Mar 12, 2015 at 0:15](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment46247449_24035852)
* `setItem` does not work for me. I tested it on chrome. the other methods work fine. – [IgniteCoders](https://stackoverflow.com/users/2835520/ignitecoders) [Jun 22, 2015 at 16:34](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#comment50000525_24035852)

[Show **5** more comments](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript)

### Not the answer you're looking for? Browse other questions tagged [javascript](https://stackoverflow.com/questions/tagged/javascript) [html](https://stackoverflow.com/questions/tagged/html) [css](https://stackoverflow.com/questions/tagged/css) [cookies](https://stackoverflow.com/questions/tagged/cookies) or [ask your own question](https://stackoverflow.com/questions/ask).
