Save And Restore Form Cookies in Javascript

CK CK 3788 
Created at  
335 0 0
This script will save all of your form fields in a cookie. It includes
all text fields,radio button selections,checkbox values,etc. When your
visitor returns,all form fields are automatically repopulated with the
same value that they entered on their last visit.

formcookie_saverestore.js
// -----------------------------------------------------//
// SAVE FORM FIELD SELECTIONS IN COOKIES         //
// formcookie_saverestore.js                //
// Written by Tony Davis,T. Davis Consulting,Inc.    //
// Date written: September 27,2005            //
// Email: tony@tdavisconsulting.com            //
// Web site: http://www.tdavisconsulting.com        //
// -----------------------------------------------------//

// instructions:
// ------------
// Change <BODY>
// to <BODY onunload="saveSelections(document.forms[0])"> and
// Change </FORM>
// TO </FORM><SCRIPT language=JavaScript type="">loadSelections(document.forms[0]);</SCRIPT>
// see a working example at: http://www.tdavisconsulting.com/formcookie
//

//
// ------------------------------------------------
// This function will concatentate all the fields in
// in the form into one string,delimited by a PIPE
// symbol,into one cookie. The cookie name is the
// same name as the form name. ALL fields are saved.
// ------------------------------------------------
//


function saveSelections(frm) {
        var setvalue;
        var fieldType;
        var index;
        var formname = frm.name;

        // Expire cookie in 999 days.
        var today = new Date();
        var exp   = new Date(today.getTime() 999*24*60*60*1000);

        var string = "formname="   formname   "|";
        var cookieName = formname;

        //alert(exp);
        //alert(formname);

        var n = frm.length;
        for (i = 0; i < n; i  )

        {
            e         = frm[i].name;
            fieldValue  = frm[i].value;
            fieldType   = frm[i].type;

            //alert(e);
            //alert(fieldType);
            //alert(fieldValue);

            //
            // RADIO BUTTON
            //
            if (fieldType == "radio") {
            //alert(frm.elements[e].length);
                for (x=0; x < frm.elements[e].length; x  ) {
                    if (frm.elements[e][x].checked)
                    {
                    index = x
                    }
                }
            string = string   index   "|";
            }

            //
            // TEXT,TEXTAREA,and DROPDOWN
            //
            if ((fieldType == "text") ||
                (fieldType == "textarea") ||
                (fieldType == "select-one"))
            {
                string = string   frm.elements[e].value   "|";
                //alert("text");
            }

            //
            // CHECKBOX
            //
            if (fieldType == "checkbox")
            {
                if (frm.elements[e].checked==true) {
                    var setvalue = "1";
                    }
                if (frm.elements[e].checked==false) {
                    var setvalue = "0";
                    }
            string = string   setvalue   "|";
            //alert("checkbox");
            }

            //
            // HIDDEN field
            //
            if (fieldType == "hidden")
            {
                string = string   frm.elements[e].value   "|";
                //alert("text");
            }
        }

//alert(string);
setCookie(cookieName,string,exp); }

//
// LOAD FORM FIELD SELECTIONS FROM SAVED COOKIES
//

function loadSelections(frm) {
var e;
var z;
var x;
var cookieName;
var fieldArray;
var fieldValues;
var fieldValue;

var formname = frm.id;

// Retrieve form elements from cookie and split into array.

cookieName  = formname;
fieldValues = getCookie(cookieName);
fieldArray  = fieldValues.split("|");

//alert(fieldArray);
//alert(fieldArray[0]);
//alert(fieldArray[1]);
//alert(fieldArray[2]);
//alert(fieldArray[3]);

        var n = frm.length;
        for (i = 0; i < n; i  ) {
            e = frm[i].name;
            z = i;
            z  ;
            var fieldType  = frm[i].type;
            var fieldValue = fieldArray[z];

            //
            // TEXT,TEXTAREA,and DROPDOWN
            //
            if ((fieldType == "text") ||
                (fieldType == "textarea") ||
                (fieldType == "select-one"))
            {
                frm.elements[e].value = fieldValue;
                //alert(e);
                //alert(fieldValue);
            }

            // CHECKBOX
            //
            if (fieldType == "checkbox")
            {
                fld_checkbox = fieldValue;
                if (fld_checkbox == "1") {
                    frm.elements[e].checked = true;
                }
            }

            // RADIO BUTTON
            //
            if (fieldType == "radio") {
                x = fieldValue;
                //alert(x);
                frm.elements[e][x].checked = true;
            }

            //
            // HIDDEN field
            //
            if (fieldType == "hidden")
            {
                frm.elements[e].value = fieldValue;
                }
        }
}

/// COOKIE FUNCTIONS

function setCookie(name,value,expires,path,domain,secure) {
document.cookie= name   "="   escape(value) 
((expires) ? "; expires="   expires.toGMTString() : "") 
((path) ? "; path="   path : "") 
((domain) ? "; domain="   domain : "") 
((secure) ? "; secure" : "");
}

function getCookie(name) {
var dc = document.cookie;
var prefix = name   "=";
var begin = dc.indexOf("; "   prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin  = 2;
}
var end = document.cookie.indexOf(";",begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin   prefix.length,end));
}


test.html
.
.
.

<script type="text/javascript" src="formcookie_saverestore.js"></script>


.
.
.

Tags Cookie Form Cookies HTML Javascript Javascript Cookie Popup Blocking Facebook X
Comments 0
Similar posts
  1. Let popup once for event dialog or something like that in Javascript
    425
  2. New content notifier in Javascript
    597
  3. Cookie Redirect
    496
  4. Cookie enabled browser checking in Javascript
    342
  5. Access Granted
    586
  6. Greeting For The Time Of Day
    393
  7. Displays the number of pages that the users browser has displayed in its session
    666
  8. Address Book
    576
  9. How to record visitor's name by Cookie
    411
  10. Basic Date Display
    511
  11. Javascript implemented Calendar
    421
  12. Javascript & Cookie based Visitor Application
    435
  13. Javascript based Alarm Clock
    666
  14. How to get date time in Javascript ?
    498
  15. Cross Browser Event Management Functions Using JavaScript
    611
  16. Hiding HTML on the browser
    461
  17. Getting WebSearchers On Your Site
    373
  18. Javascript Mouse Event Handler Example
    403
  19. Select And Deselect All Checkboxes By Javascript
    632
  20. How To Read And Write A Cookie
    363
  21. Using C# With Cookies
    625
  22. Printing A Page
    379
  23. Example Of Creating Objects
    403
  24. Linking Drop Downs
    576
  25. Roman Numerals From Integers
    511
  26. Get A Print Dialog Box By Clicking A Button
    818
  27. Keyboard event detection (Key Tracker)
    1,087
  28. IsIn For Arrays
    568
  29. Confirm The Link Clicked
    631
  30. Enlarge Image
    514
  1. Getting WebSearchers On Your Site
    373
  2. Hiding HTML on the browser
    461
  3. jQuery and Function Chaining
    536
  4. How to get date time in Javascript ?
    498
  5. Javascript based Alarm Clock
    666
  6. Javascript implemented Calendar
    421
  7. Basic Date Display
    511
  8. Address Book
    576
  9. Displays the number of pages that the users browser has displayed in its session
    666
  10. Greeting For The Time Of Day
    393
  11. Access Granted
    586
  12. Cookie enabled browser checking in Javascript
    342
  13. Cookie Redirect
    496
  14. New content notifier in Javascript
    597
  15. Let popup once for event dialog or something like that in Javascript
    425
  16. How to record visitor's name by Cookie
    411
  17. Javascript & Cookie based Visitor Application
    435
  18. Cross Browser Event Management Functions Using JavaScript
    611
  19. Printing A Page
    379
  20. Example Of Creating Objects
    403
  21. Linking Drop Downs
    576
  22. Roman Numerals From Integers
    511
  23. Get A Print Dialog Box By Clicking A Button
    818
  24. Keyboard event detection (Key Tracker)
    1,087
  25. IsIn For Arrays
    568
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260