|
A desired feature of HTML forms is to remember the input of the user. HTML forms that do not remember user input can be very annoying, if you've ever used one. Here is how to remember form input even if a user closes the browser before submitting the form, with no interaction with the server at all.
Most methods of remembering form data uses the server to remember what was submitted. This data can be referenced by a SESSION ID, COOKIES etc. Saving data on the server, however, require a HTTP Request to the server. For HTML forms, this means the form has to be submitted before the data the user filled in could be remembered.
Remembering Form Data as soon as it is entered into Input Fields
To remember form data as soon as it is entered into input fields, we can use "JavaScript Cookies". Setting a Cookie via JavaScript does not require a round trip to the server. So the cookie can be set right when the user is typing, or right after they finished typing text into a field and move to a new one. Here is an example that uses the latter.
JavaScript Code: Saves Form Data using JavaScript Cookies
Imagine that we have the HTML Form below:
<form name="form_test" id="form_test">
<p class="field">
<span class="lable">Var 1</span>
<input type="text" name="var1" />
</p>
<p class="field">
<span class="label">Var 2</span>
<input type="text" name="var2" />
</p>
<input type="submit" value="submit" />
</form>
The form consists of the two text input fields named var1 and var2 and a submit button. What we will do is attach a JavaScript onblur event handler to the text input fields, that will save their values to cookies that have the same name as each field.
To Save cookies we need a JS function that will save the cookies. (This function is borrowed, I'll add reference as soon as I remember where.)
/**
* Set a cookie
* @param string cookie name
* @param string cookie value
* @param string cookie expiration counter in days
* @param string cookie path
* @param string cookie domain
* @param bool secure?
*/
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+"="+escape( value ) +
( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
In order to retrieve Values of Cookies we need a function such as the one below.
/**
* Get a cookie value
* @param string cookie name
*/
function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
Here is the actual function that we will use to attach the JavaScript event handlers that will save the text input values to cookies (with comments).
/**
* Remebers form inputs after you fill them in
* @param string form id to remember fields
* @param string a prefix to prepend to all cookie names. (prevent naming conflicts)
*/
function rememberFormInputs(form_id, prefix) {
// get a reference to the form element with id 'form_test'
var form = document.getElementById(form_id);
// get all child input elements of the form
var els = document.getElementsByTagName('input');
// iterate through all form child input elements
for (var i = 0; i < els.length; i++) {
// this is the element with index of i
var el = els.item(i);
// make sure this is a text input field
if (el.type == 'text') {
// event handler to catch onblur events
// it sets the cookie values each time you move out of an input field
el.onblur = function() {
// this is the name of the input field
var name = this.name;
// this is the value of the input field
var value = this.value;
// set the cookie
setCookie( prefix + name, value);
alert('setCookie: '+name + ' = '+value);
};
// this inserts all the remembered cookie values into the input fields
var old_value = getCookie(prefix + el.name);
if (old_value && old_value != '') {
alert('old value remembered: '+old_value);
el.value = old_value;
}
}
}
}
The above code should be explanatory with the inline comments. Basically, what it does is iterate through each HTML Element (DOM Node) of the Form whose ID is supplied, and attaches the event handler which will save the text input field values to cookies when they are entered. It also updates all the text input fields of the form with saved values in the cookies.
Usually, we could call this function as soon as the browser window loads as in the code below:
// function will be run after window/document loads
// this initializes the form fields so they remember data after input
window.onload = function() {
rememberFormInputs('form_test', 'input-');
}
For debugging purposes, we overwrite the alert() function so that it doesn't create annoying popups but instead writes debugging info to a textarea field.
// overload alert() for debugging purposes
function alert(str) {
var el = document.getElementById('alert');
if (el) {
el.value += str+"\r\n";
}
}
View the Demo Here.
|