Skip to content

Instantly share code, notes, and snippets.

@j127
Created October 30, 2013 17:50
Show Gist options
  • Save j127/7237027 to your computer and use it in GitHub Desktop.
Save j127/7237027 to your computer and use it in GitHub Desktop.
Partial code only
function initLocalStorageControls() {
var userMessage, dataKey, dataValue, storedData, dataObj = {}, dataString = '', obj = {};
if (Modernizr.localstorage) {
console.log('Local storage is available');
$('form').fadeIn();
userMessage = 'Use the form below to add and display data.';
// Pre-fill form
storedData = localStorage.getItem('userData');
try {
obj = JSON.parse(storedData);
console.log('Successfully read the stored string into JSON: ' + obj);
Object.keys(obj).forEach(function(key) {
if (obj[key] !== null) {
console.log(key, obj[key]);
$('#' + key).val(obj[key]);
}
});
}
catch(errorObj) {
console.log('There was an error reading the stored data:');
console.log(errorObj);
}
} else {
console.log('Local storage NOT available');
userMessage = 'Sorry, local storage is not available.';
$('form').fadeOut();
}
$('#status-message').text(userMessage);
$('button#update-details').on('click', function(e) {
console.log('Button clicked');
e.preventDefault();
$('input').each(function(index) {
dataKey = $(this).attr('id');
dataValue = $(this).val();
dataObj[dataKey] = dataValue;
dataObjString = JSON.stringify(dataObj);
});
localStorage.setItem('userData', dataObjString);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment