Google Answers Logo
View Question
 
Q: Simple Javascript for setting cookie needed ( Answered 5 out of 5 stars,   3 Comments )
Question  
Subject: Simple Javascript for setting cookie needed
Category: Computers > Programming
Asked by: marcfest-ga
List Price: $25.00
Posted: 07 May 2006 12:58 PDT
Expires: 06 Jun 2006 12:58 PDT
Question ID: 726351
Hi - 

Please add javascript to the html of the page at
http://www.aftersunrise.com/remember.html, so that if the remember
checkbox is checked, then when submit is clicked, the contents of the
one line text field will be stored in a cookie and pre-filled into the
text field the next time the page is visited. If the page is visited
with the cookie "set" and therefore with the text field prefilled then
the remember check box should also be "pre-checked". Clicking the
submit button with the remember checkbox unchecked will clear any
cookie contents.

As an answer to this question, please post the html source for the
page including the added Javascript.

Thank you.

Marc.
Answer  
Subject: Re: Simple Javascript for setting cookie needed
Answered By: djbaker-ga on 08 May 2006 20:45 PDT
Rated:5 out of 5 stars
 
Greetings!
Thanks for the fun question.  Below you'll find the code which answers
your question.  I will add a follow up answer which explains what each
block of code does.

<html>
<head>
<script type="text/javascript">
//Declare the global variables
var form;
var text;
var check;

//This function sends the form as well as sets the cookie.  
function send() {
    
  
    var textvalue = input1.value; 
    var date = new Date();
    var date2 = new Date();
    date.setTime(date.getTime()+(20000*24*60*60*1000));
    
    if (check.checked) {
     
        var expires = "; expires="+date.toGMTString();
        document.cookie = "testcookie"+"="+textvalue+expires+"; path=/";
        
    }
    else {
    var expires = "; expires="+date2.toGMTString();
    document.cookie = "testcookie"+"="+" "+expires+"; path=/";
    
    }
    form.submit();

}
//This function loads on page load and checks for an existing cookie
function init() {
form = document.getElementById("form1");
text = document.getElementById("input1");
check = document.getElementById("checky");

    if (document.cookie) {
        var cookieName = "testcookie=";
        var cookie_array = document.cookie.split(';');

    for(var i=0;i < cookie_array.length;i++) {
        var c = cookie_array[i];
            while (c.charAt(0)==' ') {
             c = c.substring(1,c.length);
             }	
            
            if (c.indexOf(cookieName) == 0) {
            text.value = c.substring(cookieName.length,c.length);
            }
    }
    check.checked = true;   
}


}

</script>

</head>
<body onload="init()">
<form method="POST" action="test.cgi" name="formy" id="form1">
<p><input type="text" name="input" size="20" id="input1"></p>
  <p><input type="checkbox" name="remember" value="ON" id="checky" >remember</p>
  <p><input type="button" value="Submit" name="B1" 
onClick="send()"><input type="reset" value="Reset" name="B2"></p>
</form>





</body>
</html>

Clarification of Answer by djbaker-ga on 08 May 2006 20:58 PDT
Greetings again!
Here's how the below code works, code segments are contained within ###'s...


    
  
###    var textvalue = input1.value;  ###
   
Grabs whatever has been entered into the text box and sets it to the
variable "textvalue"


###  var date = new Date();  ###
Creates a new date object to be used in setting the cookie

### var date2 = new Date(); ###
Creates a new date object to be used in deleting the cookie

### date.setTime(date.getTime()+(20000*24*60*60*1000));  ###
Sets the first date object to some date far off into the future
    
### if (check.checked) { ###
Checks if the check box is checked.
     
### var expires = "; expires="+date.toGMTString(); ###
Sets the variable expires to a GMT string which is the proper
formating for the cookie

### document.cookie = "testcookie"+"="+textvalue+expires+"; path=/"; ###
 Set's the cookie
    
###	else {
    var expires = "; expires="+date2.toGMTString();
    document.cookie = "testcookie"+"="+" "+expires+"; path=/"; ###

If the checkbox isn't checked, it deletes the cookie

    
    }
   
### form.submit(); ###
Submits the form to the cgi script

### }
//This function loads on page load and checks for an existing cookie
function init() {
form = document.getElementById("form1");
text = document.getElementById("input1");
check = document.getElementById("checky"); ###

Retrieves an object reference to each component of the form

  ###  if (document.cookie) {
        var cookieName = "testcookie=";
        var cookie_array = document.cookie.split(';'); ###

If there is a cookie, it splits the cookie into an array containing
each individual cookie.  This is useful in the event you set multiple
cookies on the same server

###    for(var i=0;i < cookie_array.length;i++) {
        var c = cookie_array[i];
            while (c.charAt(0)==' ') {
             c = c.substring(1,c.length);
             }	
            
            if (c.indexOf(cookieName) == 0) {
            text.value = c.substring(cookieName.length,c.length);
            }
    }
    check.checked = true;   
}


####
Loops through each cookie looking for the cookie was the name
specified in "cookieName".  When it finds it outputs the value to
text.value.  Finally the checkbox is checked.


I hope this is what you are looking for.  If you have any problems,
please request a clarification and I will be more then happy to
answer.

Best,
djbaker-ga

Request for Answer Clarification by marcfest-ga on 10 May 2006 18:38 PDT
Dear djbaker - thank you for taking this one. 

Please check out http://www.aftersunrise.com/rem.html where I uploaded your code.

A few questions:

a) the check box is checked from the start. It should only be checked
when there is a cookie value present.

b) entering something in the text line field and clicking submit
causes a javascript error.

Looking forward to the fixes...

Cheers,

Marc.

Clarification of Answer by djbaker-ga on 10 May 2006 22:49 PDT
Hello again!
I'm unable to reproduce your error on my computer, which I tested it
in both Safari and Firefox.  I also tested it in internet explorer on
my girlfriends pc and could not see the problem on internet explorer
either.

So that I can download the appropriate browser to download and test it
on, which one are you using?  Also, which operating system?

I'm sorry you are having problems and I will do my best to fix them promptly.

Best,
djbaker-ga

Clarification of Answer by djbaker-ga on 10 May 2006 22:56 PDT
I apologize for my poor grammar in the previous reply.  It serves as a
compelling example of why it is best not to post in the middle of the
night.

Clarification of Answer by djbaker-ga on 10 May 2006 23:17 PDT
Okay, I've reproduced one of the problems myself on my girlfriend's
computer.  I remember testing the code specifically to check for IE
compatibility before I posted the answer last night, but for whatever
reason it no longer works now.

I still can not get the checkbox to come pre-checked however.  I do
have an idea why it is happening for you.  The code was designed to
work with the web page you specified.  I did not take into account
that you might be using cookies on the rest of your domain.  My guess
is that there is another page on your site which plants cookies, as a
result, the code logic would detect that cookie.  It is a simple fix
however, just requires one line to be shifted.

I will try to figure out what is causing the error in IE (gotta love
IE) and I will hopefully have a fix for you by tomorrow afternoon.

Sorry again for the problem.

Best,
djbaker-ga

Clarification of Answer by djbaker-ga on 10 May 2006 23:30 PDT
I fixed the offending code.  The code below should be IE compatible
now.  Please let me know if you have any more problems.

Sorry again that it did not work for you right away, I hope that it is now.

Best,
djbaker-ga

<html>
<head>
<script type="text/javascript">
//Declare the global variables
var form;
var text;
var check;

//This function sends the form as well as sets the cookie.  
function send() {
    
  
    var textvalue = text.value; 
    var date = new Date();
    var date2 = new Date();
    date.setTime(date.getTime()+(20000*24*60*60*1000));
    
    if (check.checked) {
     
        var expires = "; expires="+date.toGMTString();
        document.cookie = "testcookie"+"="+textvalue+expires+"; path=/";
        
    }
    else {
    var expires = "; expires="+date2.toGMTString();
    document.cookie = "testcookie"+"="+" "+expires+"; path=/";
    
    }
    form.submit();

}
//This function loads on page load and checks for an existing cookie
function init() {
form = document.getElementById("form1");
text = document.getElementById("input1");
check = document.getElementById("checky");

    if (document.cookie) {
        var cookieName = "testcookie=";
        var cookie_array = document.cookie.split(';');

    for(var i=0;i < cookie_array.length;i++) {
        var c = cookie_array[i];
            while (c.charAt(0)==' ') {
             c = c.substring(1,c.length);
             }	
            
            if (c.indexOf(cookieName) == 0) {
            text.value = c.substring(cookieName.length,c.length);
            check.checked = true;
            }
    }
       
}


}

</script>

</head>
<body onload="init()">
<form method="POST" action="test.cgi" name="formy" id="form1">
<p><input type="text" name="input" size="20" id="input1"></p>
  <p><input type="checkbox" name="remember" value="ON" id="checky" >remember</p>
  <p><input type="button" value="Submit" name="B1" 
onClick="send()"><input type="reset" value="Reset" name="B2"></p>
</form>





</body>
</html>
marcfest-ga rated this answer:5 out of 5 stars and gave an additional tip of: $5.00
This works wonderfully. Thank you.

Comments  
Subject: Re: Simple Javascript for setting cookie needed
From: document123-ga on 08 May 2006 04:15 PDT
 
You may find this link helpful

http://javascript.internet.com/cookies/save-and-restore-form-cookies.html
Subject: Re: Simple Javascript for setting cookie needed
From: marcfest-ga on 12 May 2006 12:12 PDT
 
djbaker -  I'd like one more tweak (and will pay for it). Please see
http://www.aftersunrise.com/forward2.cgi. The code works, but I'd like
the script to also remember the text entries in the "Your email
address" and "Your name" field, and not just in the "Email addresses
of recipents" field as is the case now. Can you adjust the source code
of that page accordingly? I'll pay another $20 for it. Thank you.
Subject: Re: Simple Javascript for setting cookie needed
From: djbaker-ga on 12 May 2006 12:48 PDT
 
Macrfest--
I'd be more then happy to do additional tweaks for you.  Simply submit
the adjustments you want made as another question and if you would
like me to personally answer them put "For djbaker-ga" in the title.

Best,
djbaker-ga

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy