SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Nov 2003
    Location
    Dundee, Scotland
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Cookie Feedback Form

    Hi

    I am trying to make a form to put on a web site that when the user enters the data into the fields and presses the submit button the info in the fields is stored in a cookie so that the next time you visit the site the fields are already filled with their name. I have seen various examples of this and even one on this site but it uses an alert box, which I don't want to use.

    I was wondering if anybody would be able to give me the easiest way in which I could do this?

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi dtennant9,

    I haven't really tested this so let me know if it doesn't work.
    Code:
    <html>
    <head>
    <script type='text/javascript'>
    
    window.onload = function()
    {
      var frm = document.forms['f1'];
      var nm = xGetCookie('name');
      if (nm) frm.nm.value = nm;
      var nt = xGetCookie('note');
      if (nt) frm.nt.value = nt;
    }
    
    function f1Onsubmit(frm)
    {
      var nm = frm.nm.value
      if (nm.length) xSetCookie('name', nm);
      var nt = frm.nt.value
      if (nt.length) xSetCookie('note', nt);
      return false; // cancel submission
    }
    
    // cookie implementations based on code from Netscape Javascript Guide
    function xSetCookie(name, value, expire, path) {
      document.cookie = name + "=" + escape(value) + ((!expire) ? "" : ("; expires=" + expire.toGMTString())) + "; path=/";
    }
    function xGetCookie(name) {
      var value=null, search=name+"=";
      if (document.cookie.length > 0) {
        var offset = document.cookie.indexOf(search);
        if (offset != -1) {
          offset += search.length;
          var end = document.cookie.indexOf(";", offset);
          if (end == -1) end = document.cookie.length;
          value = unescape(document.cookie.substring(offset, end));
        }
      }
      return value;
    }
    </script>
    </head>
    <body>
    
    <form id='f1' onsubmit='return f1Onsubmit(this)'>
      <p>Name: <input type='text' name='nm'></p>
      <p>Note: <input type='text' name='nt'></p>
      <p><input type='submit' value='Save To Cookies'></p>
    </form>
    
    </body>
    </html>

  3. #3
    SitePoint Member
    Join Date
    Nov 2003
    Location
    Dundee, Scotland
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Talking

    Thanks very much. It works like an absolute dream


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •