Skip to content

Instantly share code, notes, and snippets.

@andeersg
Created February 5, 2014 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andeersg/8826391 to your computer and use it in GitHub Desktop.
Save andeersg/8826391 to your computer and use it in GitHub Desktop.
Perform backup and restoration of form values.
jQuery.support.localstorage = function() {
var mod = 'modernizr';
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
}
jQuery(document).ready(function($) {
if ($.support.localstorage()) {
reload_state();
var currentState = [];
$('form').change(function(){
currentState = [];
$("form *").filter(':input:not(:file)').each(function(){
//console.log($(this));
var temp = {
'id': $(this).attr('id'),
'value': $(this).val()
}
currentState.push(temp);
});
localStorage['currentState'] = JSON.stringify(currentState);
});
}
function reload_state() {
if (localStorage.getItem("currentState") !== null) {
var currentState = JSON.parse(localStorage["currentState"]);
$.each(currentState, function(i, v){
if (typeof v.id !== 'undefined' && v.value !== '') {
$('#' + v.id).val(v.value);
}
});
}
}
function clear_state() {
if (localStorage.getItem("currentState") !== null) {
localStorage.removeItem('currentState');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment