Unit 2B
Updated version
by Larry Adams
HTML
<fieldset>
<legend>Contact List</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="email">Email:</label><br>
<input type="text" id="email"></div>
<br>
<div><label for="phone">Phone:</label>
<br>
<input type="text" id="phone"></div>
<br> <br>
<input type="button" id="addContact" value="Add Contact" />
<table>
<th>
</th>
<tr>
<td></td>
</tr>
</table>
</fieldset>
JavaScript
console.clear();
// Array to hold Contact Objects
contact = [];
var Contact = function(fName, lName, email, phone) {
this.fName = fName;
this.lName = lName;
this.email = email;
this.phone = phone;
this.getContact = function() {
return this.fName + " " + this.lName + this.email + this.phone;
}
}
// add contacts to the Array
var addContact = document.getElementById('addContact');
addContact.onclick = function() {
var fName = document.getElementById('fName').value;
var lName = document.getElementById('lName').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
if(fName.length > 0 && lName.length > 0 && email > 0 && phone > 0) {
console.log(this.fName + " " + this.lName + this.email + this.phone);
} else {
console.log("Please complete all fields");
}
}
/*
contacts.push(new Contact(contactfNameFromForm, contactlNameFromForm, contactemailFromForm, contactphoneFromForm));
//contacts.push(new Contact("John", "Adams", "[email protected]", 3049877887));
//contacts.push(new Contact("Abigail", "Adams", "[email protected]", 3049877887));
// print the contacts to the console
console.log('There are ' + contacts.length + ' contacts in the contacts Array:');
console.log(contacts);
console.log(' ');
// convert contact OBJECT to a String
var jsonContact = JSON.stringify(contacts);
console.log('JSON.stringify(contacts):');
console.log(jsonContact);
console.log(' ');
// store the string in local storage
window.localStorage.setItem("contacts", jsonContact);
// clear out existing contacts from the array
contacts = [];
console.log('There are ' + contacts.length + ' contacts in the contacts Array:');
console.log(contacts);
console.log(' ');
// check for contacts in local storage
var checkContacts = window.localStorage.getItem('contacts');
if (checkContacts != undefined) {
checkContacts =...