why aren’t the cookies saved when i run the following script:
window.onload=init;
function init() {
var userName="";
if(document.cookie != "") {
username=document.cookie.split("=")[1];
}
document.getElementById("name_field").value = username;
document.getElementById("name_field").onblur = setCookie;
}
function setCookie() {
var exprDate = new Date();
exprDate.setMonth(exprDate.getMonth() + 6);
var userName = document.getElementById("name_field").value;
document.cookie = "username=" + username + ";path=/;expires=" + exprDate.toGMTString();
}
When i refresh the page the text-field gets empty? why is so ?
HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="writing_cookie.js">
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
<input type="submit" value="submit" />
</form>
</body>
</html>
As @pimvdb says, you mix the case of username.
In javascript, things are case sensitive – userName is not the same variable as username so you need to be consitant with your casing.
The specific problem is that you assign the value of the name_field to userName in setCookie() but on the next line you save username to the cookie. username is uninitialised so you save an empty value to the cookie. This empty value is what you get from the cookie in init()
Also, in init() you declare userName but assign the value of the cookie to username. This doesn’t actually cause a problem but it could do with fixing all the same.
Edit – I’ve just seen your reply to @pimvdb’s comment and done a bit more research:
When reading the cookie, you need to split on “;”, not “=”. This will then give you an array of “username=username”, “path=path” and “expires=date”. You then would extract the username from the first element of the array by looking for the “=”
Your code splits on “=” which would give an array of “username”, “username;path”, “/;expires” and “date“.
I would have expected it to have put something in the text field with your code though (after you’d fixed the casing issue).
(Reference page here)