Skip to content

Instantly share code, notes, and snippets.

@dimitrikennedy
Created March 9, 2012 15:03
Show Gist options
  • Save dimitrikennedy/2006881 to your computer and use it in GitHub Desktop.
Save dimitrikennedy/2006881 to your computer and use it in GitHub Desktop.
JavaScript: Save JSON to Local Storage
$('#submit').click(function() {
var info = {
"name": $('#name').val(),
"age": $('#age').val(),
"bio": {
"short": $('#bio').val(),
"long": $('#bioLong').val()
}
}
localStorage.setItem("info", JSON.stringify(info));
console.log(JSON.parse(localStorage.info));
});
$('#print').click(function() {
var thejson;
if (typeof localStorage.info === 'undefined') {
$('body').append('<li>local storage is empty</li>');
} else {
thejson = JSON.parse(localStorage.info);
name = thejson.name, age = thejson.age, bio = thejson.bio.short;
biolong = thejson.bio.long;
$('body').append('<li><ul><li>' + name + ' is ' + age + ' years old</li><li>' + bio + '</li><li>' + biolong + '</li></ul></li>');
}
});
$('#clear').click(function() {
localStorage.clear()
$('li').remove();
});​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment