Skip to content

Instantly share code, notes, and snippets.

@xarg
Created September 2, 2010 09:31
Show Gist options
  • Save xarg/562093 to your computer and use it in GitHub Desktop.
Save xarg/562093 to your computer and use it in GitHub Desktop.
/**
* This is an example to create persistent forms using
* HTML5 localStorage + jQuery serialization and
* url.decode from http://www.webtoolkit.info/
*
*
* The example bellow is seriously unoptimized.
* It listens to changing events in the form and
* serializes the data of the form in localStorage
*/
$(':input').change(function(){
localStorage.form = $(this).parents('form').serialize();
});
if (localStorage.form){ //populate the form if the page was refreshed
unserialize(localStorage.form);
}
/**
*
* URL encode / decode
* http://www.webtoolkit.info/
*
**/
function url_decode(utftext) {
utftext = unescape(utftext)
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
function unserialize(data){
var rows = data.split('&');
$.each(rows, function(i, row){
var field = url_decode(row).split('=');
var field_el = $(':input[name='+ field[0] +']');
/**
* Other input types must be verified
*/
if(field_el.attr('type') == 'checkbox'){
field_el.attr('checked', field[1]);
}else{
field_el.val(field[1]);
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment