Setting a Cookie

Discussion in 'JavaScript' started by Morn, Feb 20, 2007.

  1. #1
    I have this code and i can not get it to set the cookie.

    Is there anythng obvious that i am missing?

    The button that calls the function:

    <input type = "submit" value = "Submit" onclick = "setCookie()" />
    Code (markup):
    The code that sets the cookie:

    window.onload = usercookieset; //calls function usercookieset to either create cookie or check the value
                    
            function usercookieset(){ //sets the function
                var userName = "";//declares the variable with a null value
                if (document.cookie != ""){//tests the value of the cookie to see if its not set to null
                    userName = document.cookie.split ("=")[1];
                    
                document.getElementById("username").value = userName;//retrieves the value of the username text field and stores it in the userName variable               
                   }
            
            
            function setCookie(){ //function that is called to run the above function
                var expireDate = new Date();//gets the date and stores it as a variable
                expireDate.setMonth(expireDate.getMonth()+12);//sets the expiry time of the cookie
                
                var userName = document.getElementById("username").value;
    	        document.cookie = "userName=" + userName + ";expires=" + expireDate.toGMTString();
            }
    
    
    Code (markup):
     
    Morn, Feb 20, 2007 IP
  2. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #2
    You're setting an invalid month value, so the cookie will expire instantly. Use:
     expireDate.setDate( expireDate.getDate() + numberOfDays );
    Code (markup):
     
    Logic Ali, Feb 20, 2007 IP