JavaScript Code

Retain Form Input Values with JavaScript

HTML is stateless. If you're typing information into form fields, and you refresh the page for some reason, the data is not stored, and you have to retype it. Or, if a user misses a field or inputs incorrect information, it's necessary to ask them to fix, while retaining the values they've already entered. With many programming languages this is done by accessing the POST information. But what if you're working with just HTML? Or what if you don't submit the form, you just refresh it? This JavaScript functionality will enable you to store form data as it's entered, so it can retrieved even if you refresh the page.

This code works by storing each field value in a cookie as the user leaves that field (onblur). Also, as you enter into the field, it checks the cookie to see if a value is present, and if so populates the field.

If you have a large number or fields, it would be easier to create a function that loops through all fields and adds the onfocus/onblur events dynamically at page load, rather than manualyl entering each one.


<script language="JavaScript" type="text/javascript">
function setValue(element) {
    var exp = new Date();                                   
    exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 31));
    setCookie(element.name, element.value, exp);
}

function getValue(element) {
    var val = getCookie(element.name);
    if (val != null) 
        element.value = val;
}

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

function getCookie( name ) {
    var dc = document.cookie;
    var strPrefix = name + '=';
    var intStart = dc.indexOf( '; ' + strPrefix );
    if ( intStart == -1 ) { intStart = dc.indexOf( strPrefix ); }
    if ( intStart == -1 ) {
        return null;
    } else {
        var intEnd = document.cookie.indexOf( ';', intStart );
        if ( intEnd == -1 ) { intEnd = dc.length; }
        return unescape( dc.substring( intStart + strPrefix.length, intEnd ) );
    }
}
</script>

And here's the code you'll put into each field:


First Name:  <input type="text" name="firstname" onfocus="getValue(this)" onblur="setValue(this)" /><br />

Last Name:  <input type="text" name="lastname" onfocus="getValue(this)" onblur="setValue(this)" />
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image