setcookie-js.js

/* Set a cookie based on value entered in input box by visitor.
 */

// Set up event handlers
// Whenever the content of the box changes, the cookie will be (re)set.
// Clicking the Show Cookie button will display document.cookie in an alert box
window.onload = function() {
    document.getElementById("visitor_name").onchange = setCookie;
    document.getElementById("showButton").onclick = showCookies;
};

// Set cookie named "visitor_name", with value equal to what the visitor entered
function setCookie() {
    // set cookie name and value into variables
    var cookieName = "visitor_name";
    var cookieValue = document.getElementById("visitor_name").value;
    if( !cookieValue ) return;	// ignore if box is empty

    // Expire the cookie in one month
    var expireDate = new Date();
    expireDate.setMonth(expireDate.getMonth()+1);

    // Set the cookie.
    // Escape any special characters in cookie value.
    document.cookie = cookieName + "=" + encodeURIComponent(cookieValue) +
	"; expires=" + expireDate.toUTCString(); 
}

// Show the document.cookie string in an alert box
function showCookies() {
    window.alert(document.cookie);
}