Local Storage API, Storing and Retrieving Simple Data, Arrays, Associative Arrays, and Objects
Video
Presentation Link
Example #1
This code creates a few items. It creates an array of names for everyone in our group and stores that array in local storage. Then it stores the course name in a sessionStorage array.Javascript Code:
var names = ["Jan", "Tif", "Mark", "Chuck", "Olan"];
var course = "CIT 261 Section 2 Winter 2017";
var car = {make:"Honda", model:"Odyssey", year:"2012", color:"white"};
localStorage.setItem("names", JSON.stringify(names));
localStorage.setItem("car", JSON.stringify(car));
sessionStorage.setItem("course", course);
Next Page
Example #2
This example shows the storage of an array of Contact objects. This shows both the storage and retrieval of that array.
Contact Input
Contact List
FOREACH Loop Code Snippet
function Contact(name, phone, address, email) {
this.name = name;
this.phone = phone;
this.address = address;
this.email = email;
}
function addContact() {
var nameElement = document.getElementById('name');
var phoneElement = document.getElementById('phone');
var addressElement = document.getElementById('address');
var emailElement = document.getElementById('email');
var name = nameElement.value;
var phone = phoneElement.value;
var address = addressElement.value;
var email = emailElement.value;
var newContact = new Contact(name, phone, address, email);
var contactList = JSON.parse(localStorage.getItem("contactList"));
if(contactList === null) {
contactList = Array();
}
contactList.push(newContact);
localStorage.setItem("contactList", JSON.stringify(contactList));
nameElement.value = "";
phoneElement.value = "";
addressElement.value = "";
emailElement.value = "";
updateTable();
}