First page Back Continue Last page Image
- <!DOCTYPE html>
- <html>
- <head>
- <title>Set a cookie based on a form</title>
- <script src="script01.js"></script>
- </head>
- <body>
- <form id="cookieForm" action="#"> <h1>Enter your name: <input type="text" id="nameField"> </h1> </form>
- </body> </html>
- window.addEventListener("load",nameFieldInit,false);
- function nameFieldInit() {
- var userName = "";
- if (document.cookie != "") {
- userName = document.cookie.split("=")[1];
- }
- document.getElementById("nameField").value = userName;
- document.getElementById("nameField").onblur = setCookie;
- document.getElementById("cookieForm").onsubmit = setCookie;
- }
- function setCookie() {
- var expireDate = new Date();
- expireDate.setMonth(expireDate.getMonth()+6);
- var userName = document.getElementById("nameField").value;
- document.cookie = "userName=" + userName + ";expires=" + expireDate.toGMTString();
- document.getElementById("nameField").blur();
- return false;
- }
- document.cookie.split(“=“)
- This line actually creates the cookie
- "userName=Nicole Cook; expires=Sat, 24 Sep 2016 12:00:00 UTC "
- This is what our cookie looks like