Save / Retrieve Cookies and Form Field Values with Javascript
I had a need to store form field values in a cookie so that the next time the form field was shown, within the same session, it could populate the values from the previous form submission. This is useful when there are more than one of the same forms being filled out with data, but some of the data will probably be the same, such as address, company name, etc.
Requirements
- store text field value in cookie
- retrieve and update text field if cookie exists
Process Flow
- type value in text field
- click submit button
- loop through form
- if form field type is text and class contains “save”, store value in cookie
- when form pops up again, loop through form
- if form field type is text and class contains “save”, retrieve value in cookie and put in text field
JavaScript Functions
- saveFields(Form) – Form is the name of the form. For example, if html has <form name=”testform”…, then you would call saveFields with saveFields(‘testform’). This is useful if the saveFields function is called outside of the form, or from a different function.
- saveFieldsSubmit(Form) – Form is the object of the form. Example, <form name=”testform” onsubmit=”return saveFieldsSubmit(this)”… This is the most common use of this process.
- loadFields(Form) – Form is the name of the form. For example, if html has <form name=”testform”…, then you would call loadFields with loadFields(‘testform’). This function is usually called through JavaScript at the bottom of the page.
- Cookie Functions for saving, retrieving and erasing were created by Scott Andrew (http://www.scottandrew.com/), and copied from the site http://www.quirksmode.org/js/cookies.html.
Setup
- copy the javascript block from below into the html, just above the </body> tag, or somewhere after the </form>. This is done simply because the loadFields function is called in the script. You can certainly move things around, but the loadFields should be called after the </form>. A thought would be to create a loadFields method that loops through all forms in the page instead of just being called by the name of the form…
- put “save” into the class property of any text field you wish to save. For example, <input type=”text” class=”std_text save”… or <input type=”text” class=”save”…
- add saveFieldsSubmit(this) to the onsubmit property. <form name=”frmTestForm” id=”frmTestForm” onsubmit=”return saveFieldsSubmit(this);”…
That’s all there is to it!
The code can be found here.
