2

This is my script.

<script>
        function save() {
            var x=document.getElementById("user").value;
            var y=document.getElementById("password").value;
            document.cookie=x+" "+y;
        }
        function write() {
            document.write(document.cookie);
        }
</script>

This works fine, it remembers the value of var x and y and writes them when function write() is called. When I close the browser the cookie gets deleted, as it should. But I would like to set an expire date of one year; I tried in many ways but I really can't get it to work. Any help?

Omarino99
  • 39
  • 1
  • 1
  • 2
  • Look at [this question at SO][1], it should help you. [1]: http://stackoverflow.com/questions/13154552/javascript-set-cookie-with-expire-time – Frodik May 24 '15 at 11:08

3 Answers3

5

Add a max-age segment:

 ;max-age=<max-age-in-seconds>

Documentation here

This would expire your cookie in a day:

    function save() {
        var x=document.getElementById("user").value;
        var y=document.getElementById("password").value;
        document.cookie=x+"="+y+";max-age="+(3600*24);
    }

I recommend using a library for setting cookies, because there are a lot of gotchas when setting/reading cookies cross-browser. For example the js-cookie library.

Note: it's bad practice to store a plaintext password in a cookie. You're probably looking for a session cookie.

Blaise
  • 13,139
  • 9
  • 69
  • 97
1

This is an example from w3schools.

document.cookie="cookiename=cookievalue; expires=Thu, 18 Dec 2013 12:00:00 UTC";
The_ehT
  • 1,202
  • 17
  • 32
1

You just need to write

document.cookie = "cookiename=value; expires= 03 Dec 2015 00:00"

However, if you just type "javascript cookies" on Google you can find this page: http://www.w3schools.com/js/js_cookies.asp it's very useful.

Drago96
  • 1,265
  • 10
  • 19