Reputation: 39
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
Reputation: 13479
Add a max-age segment:
;max-age=<max-age-in-seconds>
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
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