Omarino99
Omarino99

Reputation: 39

How to set cookie's expire date with js?

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?

Upvotes: 2

Views: 17746

Answers (3)

Blaise
Blaise

Reputation: 13479

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.

Upvotes: 6

Drago96
Drago96

Reputation: 1407

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.

Upvotes: 1

The_ehT
The_ehT

Reputation: 1230

This is an example from w3schools.

document.cookie="cookiename=cookievalue; expires=Thu, 18 Dec 2013 12:00:00 UTC";

Upvotes: 1

Related Questions