Search code examples
javascriptcookiesexpired-cookies

How to set a cookie's expiration date in Javascript


I am trying to make a cookie that expires on a specific date. On w3schools they said to set it using

document.cookie="mediaType=Video; expires=Fri, 13 Mar 2015 12:00:00 UTC";

However in my code it doesn't seem to be working. What am I doing wrong?

<script>
    var mediaType = "image";
    function checkCookies(){
            document.getElementById("div").innerHTML = document.cookie;
    }
    function getType() {
        document.cookie="mediaType=Video; expires=Fri, 13 Mar 2015 12:00:00 UTC";
        document.getElementById("div").innerHTML = document.cookie
    }
</script>

<body onload="checkCookies()">
    <select onChange="mediaType = this.value">
      <option value="image">Image</option>
      <option value="link">Link</option>
      <option value="text">Text</option>
    </select>
</body>

<div id="div" onclick="getType()"> hi</div>

BONUS is there a way to set a cookie as the value of a variable?


Solution

  • The method you are using for setting the cookie is correct but at start the values are not showing because there are no cookies. Remember that you only can access the cookies set by your site so at start there aren't any. You can add a test cookie to see that your code is working like in the following example, also it shows how to update the value of the cookie when the select is changed as you asked:

    <script>
    function checkCookies(){
        document.cookie="Test=Test Cookie; expires=Fri, 13 Mar 2015 12:00:00 UTC";
        document.getElementById("div").innerHTML = document.cookie;
    }
    function updateCookies(val) {
        document.cookie="mediaType="+ val +"; expires=Fri, 13 Mar 2015 12:00:00 UTC";
        document.getElementById("div").innerHTML = document.cookie;
    }
    </script>
    
    <body onload="checkCookies()">
      <select onChange="updateCookies(this.value)">
        <option value="image">Image</option>
        <option value="link">Link</option>
        <option value="text">Text</option>
      </select>
    
      <div id="div"> hi</div>
    
    </body>