zaus / FormRepo.js

Save zaus/4717416 to your computer and use it in GitHub Desktop.

Preserve form values across page loads -- i.e. persistent forms. Uses `localStorage` to persist, `jQuery` for utilities.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

var FormRepo = function ( namespace )
/// Persistent form values, saves to localStorage
/// the namespace to store values in localStorage
// should also protect per page, since we could have the same forms in various places
this . N = namespace + '.' + window . location . pathname ;
> ;
$ . extend ( FormRepo . prototype ,
namespace : function ( key )
return this . N + '.' + key ;
>
,
preserve : function ( $form , iden )
var data = $form . serializeArray ( ) ;
localStorage . setItem ( this . namespace ( 'form.' + ( iden || $form . index ( ) ) ) , JSON . stringify ( data ) ) ;
>
,
restore : function ( $form , iden )
var data = localStorage . getItem ( this . namespace ( 'form.' + ( iden || $form . index ( ) ) ) ) ;
if ( null == data || $ . isEmptyObject ( data ) ) return ; // nothing to do
$ . each ( JSON . parse ( data ) , function ( i , kv )
// find form element, set its value
var $input = $form . find ( '[name=' + kv . name + ']' ) ;
// how to set it's value?
if ( $input . is ( ':checkbox' ) || $input . is ( ':radio' ) )
$input . filter ( function ( ) < return $ ( this ) . val ( ) == kv . value ; >) . first ( ) . attr ( 'checked' , 'checked' ) ;
>
else
$input . val ( kv . value ) ;
>
> ) ;
> //-- fn restore
,
remove : function ( $form , iden )
localStorage . removeItem ( this . namespace ( 'form.' + ( iden || $form . index ( ) ) ) ) ;
> //-- fn remove
,
all : function ( )
var allData = < >;
for ( var i = 0 , l = localStorage . length ; i < l ; i ++ )
allData [ localStorage . key ( i ) ] = localStorage . getItem ( localStorage . key ( i ) ) ;
>
return allData ;
> //-- fn repo.all
> ) ;