Project 2B

by Larry Adams

HTML

<h2>Unit 2 B Project</h2>
    <p>Student: Larry L. Adams II</p>
    
<fieldset>
    <legend>Enter Contact</legend>
    <br>
    <div>
        <label for="fname">First Name:</label><br>
            <input type="text" id="fname" />
    </div>
        <br>
        <div>
        <label for="lname">Last Name:</label><br>
            <input type="text" id="lname" />
    </div>
        <br>
        <div>
        <label for="phone">Phone #:</label><br>
            <input type="text" id="phone" />
    </div>
        <br>
        <div>
        <label for="email">Email:</label><br>
            <input type="text" id="email" />
    </div>
    
            <br> <br>
        <button type="button" id="saveBtn">Save Contact</button>
        <button type="button" id="clearLSBtn">Clear Contact</button>    
</fieldset>

<br>
    <hr>
        <br>
            
    <fieldset>
        <legend>Contact List</legend>
        <div id="output"></div>
    </fieldset>

JavaScript

"use strict";

console.clear();

// Array to hold person Objects
var contact = [];
function Contact(fName, lName, phone, email) {
    this.fName = fName;
    this.lName = lName;
    this.phone = phone;
    this.email = email;
    this.getContact = function() {
        return this.fName + " " + this.lName + " " + this.phone + " " + email;
    }
}

// checking localStorage
console.log(window.localStorage);

people.push(new Person("John", "Harvard"));
people.push(new Person("Mickey", "Mouse"));
people.push(new Person("Donald", "Duck"));

var peopleLen = people.length;
for (var i = 0; i < peopleLen; i++) {
    console.log(people[i].getPerson());
}

// convert Array to String so we can persist it in localStorage
var myPeople = JSON.stringify(people);

// persist people Array in localStorage
localStorage.setItem('people', myPeople);

// check for people in local storage
var data = window.localStorage.getItem('people');
if (data) {
    // parse the people
    var myData = JSON.parse(data);
    console.log(myData);

    // loop through myData and display key/value pairs
    console.log('Key / Value pairs:');
    myData.forEach(function(p) {
        for (var key in p) {
            console.log("The person's " + key + " is " + p[key] + ".");
        }
        console.log(' ');
    });
        
    // loop through myData and show data
    console.log("People:");
    var len = myData.length;
    for (var i = 0; i < len; i++) {
        console.log(myData[i].fName + " " + myData[i].lName);
    }
    console.log(' ' );

    var myNewPeople = [];
    console.log("There are " + myNewPeople.length + " Objects in the Array.");

    // loop through myData, create new Person Objects with the data, and push them to the myNewPeople Array
    myData.forEach(function(p) {
        myNewPeople.push(new Person(p.fName, p.lName));
    });
    console.log("There are " + myNewPeople.length + " Objects in the Array.");
} else {
    console.log("No people to process.");
}