Skip to content

Instantly share code, notes, and snippets.

@mchayapol
Created September 14, 2015 03:29
Show Gist options
  • Save mchayapol/6340937ebbeeba006021 to your computer and use it in GitHub Desktop.
Save mchayapol/6340937ebbeeba006021 to your computer and use it in GitHub Desktop.
JSON Example 02 (Add Contact)
<!DCOTYPE html>
<head>
<title>Test</title>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
/*
// dynamic-length record, delimiter
localStorage.contact = "Chayapol|Moemeng|pic.jpg|08989999|[email protected]";
// tokenize contact with |, NAH
*/
// JSON - JavaScript Object Notation
var contactData = {
"contacts": [
{
"firstname": "Chayapol",
"lastname": "Moemeng",
email: "[email protected]",
phone: "089999999",
avatar: "avatar.png"
},
{
"firstname": "Anna",
"lastname": "Smith",
email: "[email protected]",
phone: "088888888",
avatar: "avatar.png"
}
]
};
// Simple example
var contactA = {
"firstname": "Anna",
"lastname": "Smith",
email: "[email protected]",
phone: "088888888",
avatar: "avatar.png"
};
console.log(contactA);
// Load all contacts into div2
console.log(localStorage.contactList);
// It could happen that localStorage.contactList has never been defined.
// So, you'll get 'undefined'.
var list;
if (typeof localStorage.contactList === "undefined") {
list = [];
} else {
list = JSON.parse(localStorage.contactList);
}
var listHTML;
for (var c in list) {
console.log('c'+c);
listHTML += "<li>" + c.firstname + " " + c.lastname + "</li>";
}
$('#div2').html("<ul>" + listHTML + "</ul>");
//localStorage.contact = JSON.stringify(contactA);
var tempContact = JSON.parse( localStorage.contact );
console.log(tempContact);
$('#firstname').val(tempContact.firstname);
$('#lastname').val(tempContact.lastname);
$('#name').html( );
// Add button event handler (an annonymous callback function)
$('#btn1').click(
function () {
// Add to the list and
// Update the current localStorage.contactList
tempContact.firstname = $('#firstname').val();
tempContact.lastname = $('#lastname').val();
console.log($('#firstname').val() + '--' + tempContact.firstname);
list[list.length] = tempContact;
localStorage.contactList = JSON.stringify(list);
console.log(JSON.stringify(tempContact));
localStorage.setItem("contact",JSON.stringify(tempContact));
}
);
});
</script>
</head>
<html>
<body>
<div id="div1">
<input type="text" id="firstname" /><br />
<input type="text" id="lastname" /><br />
<span id="name"></span>
<button id="btn1">Add Contact</button>
</div>
<div id="div2"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment