onlyforbopi
9/27/2018 - 8:43 AM

JS Bin // source https://jsbin.com/mayuwik

JS Bin

// source https://jsbin.com/mayuwik

window.onload = init;

// The contact manager as a global variable
let cm; 

// button control
var saveBtn, emptyBtn, loadBtn;

function init() { 

  // get buttons reference 
  saveBtn = document.querySelector('.save'); 
  emptyBtn = document.querySelector('.empty'); 
  loadBtn = document.querySelector('.load');

  // listen to their click event
  saveBtn.addEventListener('click', saveData);  
  emptyBtn.addEventListener('click', eraiseData);  
  loadBtn.addEventListener('click', loadData);  

	// create an instance of the contact manager
	cm = new ContactManager();
	
  	cm.addTestData();
  	cm.printContactsToConsole();

	  // Display contacts in a table
	  // Pass the id of the HTML element that will contain the table
	  cm.displayContactsAsATable();
}

function saveData(evt) {
  cm.save();
  cm.printContactsToConsole();
}

function eraiseData(evt) {
  cm.empty();
  cm.displayContactsAsATable();
}

function loadData(evt) {
  cm.load();
  cm.displayContactsAsATable();
}

function formSubmited() {
  // Get the values from input fields
  var name = document.querySelector('#name');
  var email = document.querySelector('#email');

  // create an new contact for them
  var newContact = new Contact(name.value, email.value);

  // add the new contact to list of contact
  cm.add(newContact);

  // Empty the input fields
  name.value = '';
  email.value = '';

  // refresh the table
  cm.displayContactsAsATable();

  // do not let your browser submit the form using HTTP
  return false;
}

class Contact {
	constructor(name, email) {
		this.name = name;
		this.email = email;
	}
}

class ContactManager {
	constructor() {
		// when we build the contact manager, it
		// has an empty list of contacts
		this.listOfContacts = [];
	}

  // add some data usefull for testing
  addTestData() {
    // Generate 4 arbitrate contact
		let c1 = new Contact('Pedrito', 'Pedrito@hotmail.fr');
		let c2 = new Contact('Kader', 'Kader@hotmail.fr');
		let c3 = new Contact('Samir', 'Samir@hotmail.fr');
		let c4 = new Contact('Amin', 'Amin@hotmail.fr');
		
    // add them to list of contact
    this.add(c1);
    this.add(c2);
    this.add(c3);
    this.add(c4);
  
    // sort them by name
    this.sort();
  }
	
  // Will erase all contacts
	empty() {
		this.listOfContacts = [];
	}
	
	add(contact) {
		this.listOfContacts.push(contact);
	}
	
	remove(contact) {
		for(let i = 0; i < this.listOfContacts.length; i++) { 
			var c = this.listOfContacts[i];

			if(c.email === contact.email) {
				// remove the contact at index i
				this.listOfContacts.splice(i, i);
				// stop/exit the loop
				break;
			}
		}
	}
	
	sort() {
		// As our array contains objects, we need to pass as argument
		// a method that can compare two contacts.
		// we use for that a class method, similar to the distance(p1, p2)
		// method we saw in the ES6 Point class in module 4
		// We always call such methods using the name of the class followed
		// by the dot operator
		this.listOfContacts.sort(ContactManager.compareByName);
	}
	
	// class method for comparing two contacts by name
	static compareByName(c1, c2) {
		// JavaScript has builtin capabilities for comparing strings
		// in alphabetical order
		if (c1.name < c2.name) {
      return -1;
    }	
    if (c1.name > c2.name) {
      return 1;
    }
    return 0;
	}
	
	printContactsToConsole() {
		if(this.listOfContacts.length === 0) {
			console.log("EMPTY LIST!");
			return;
		}
		
		this.listOfContacts.forEach(function(contact) {
			console.log(contact.name);
		});
	}
	
	load() {
		if(localStorage.contacts !== undefined) {
			// the array of contacts is saved in JSON format 'String', let's convert
			// it back to a real JavaScript object.
			this.listOfContacts = JSON.parse(localStorage.contacts);
		}
	}
	
	save() {
		// We can only save strings in local Storage. So, let's convert
		// ou array of contacts to JSON
		localStorage.contacts = JSON.stringify(this.listOfContacts);
	}

  displayContactsAsATable() {
    // empty the container that contains the results
    let container = document.querySelector('.container');
    container.innerHTML = '';

		if(this.listOfContacts.length === 0) {
			container.innerHTML = '<p>No contacts to display!</p>';
			// stop the execution of this method
			return;
		}  
  
   // creates and populate the table with users
   let table = document.createElement('table');
    // create table caption
    let caption = table.createCaption();
    // set content to it
    caption.innerHTML = 'CONTACT MANAGER PROJECT';
    // create table header
    let thead = table.createTHead();
    // fill it width some content
    thead.innerHTML = '<tr>' + 
                         '<th scope="col">NAME</th>' +
                         '<th scope="col">EMAIL</th>' +
                      '</tr>';
    // create table body
    let tbody = table.createTBody();

    // create table footer
    let tfoot = table.createTFoot();
    // fill it width some content
    tfoot.innerHTML = '<tr><th colspan="2">THESE ARE OUR CUSTOMER</th></tr>';

    this.listOfContacts.forEach(function(currentContact){
      // generate a row for currentContact
      var row = tbody.insertRow();
      // currentContact is an object
      // so loop on its properties
      for (const key in currentContact) {
        if (currentContact.hasOwnProperty(key)) {
          // generate a cell for each prop of the currentContact
          const cell = row.insertCell();
          const prop = currentContact[key];
          cell.innerHTML = prop;
        }
      }
      // each iteration we add the row to the tbody
      tbody.appendChild(row);
    });  
    // finaly add table to the container
    container.appendChild(table);  
  }
}
* {
  margin: 0;
  padding: 0;
  border: none;
  outline: none; 
}

body {
  font-size: 16px;
}

h1 {
  text-align: center;
  font-size: 1.5rem;
  margin: 2% 0;
}

form {
  min-width: 25%;
  max-width: 45%;
  margin: auto;
}

fieldset {
  border: 1px solid;
  padding:10px;
  border-radius:10px;
}

legend {
  text-align: center
}

label {
  width:150px;
  text-align: right;
  display:inline-block;
  margin-bottom:10px;
}

input {
  float:right;
  margin-right:70px;
  width:150px;
  padding: 3px;
  border-radius: 10px;
}

input:invalid {
  background-color:lightpink;
}

input:valid {
  background-color:lightgreen;
}

fieldset button {
  display: block;
  margin: auto;
  border: 0.5px silver solid;
  box-shadow: 5px 5px 5px lightcyan;
  background-color: azure;
  padding: 10px;
  border-radius: 10px;
}

.controls {
  min-width: 35%;
  max-width: 50%;
  display: flex;
  margin:1.5% auto;
  justify-content: space-around;
}

.controls button {
  width: 15%;
  border: none;
  border-radius: 20px;
  padding: 5px;
  background-color: bisque;
}

.container {
  min-width: 50%;
  max-width: 65%;
  margin: auto;
}

p {
  text-align: center;
  font-size: 2rem;
}

table {
  width:100%;
  border: 1px solid;
  border-collapse: collapse;
}

th {
  background-color: coral;
}

th, td {
  border: 1px solid;
  text-align: center;
  padding: 5px;
} 

tbody tr:nth-child(even) {
  background-color: cornflowerblue;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<style id="jsbin-css">
* {
  margin: 0;
  padding: 0;
  border: none;
  outline: none; 
}

body {
  font-size: 16px;
}

h1 {
  text-align: center;
  font-size: 1.5rem;
  margin: 2% 0;
}

form {
  min-width: 25%;
  max-width: 45%;
  margin: auto;
}

fieldset {
  border: 1px solid;
  padding:10px;
  border-radius:10px;
}

legend {
  text-align: center
}

label {
  width:150px;
  text-align: right;
  display:inline-block;
  margin-bottom:10px;
}

input {
  float:right;
  margin-right:70px;
  width:150px;
  padding: 3px;
  border-radius: 10px;
}

input:invalid {
  background-color:lightpink;
}

input:valid {
  background-color:lightgreen;
}

fieldset button {
  display: block;
  margin: auto;
  border: 0.5px silver solid;
  box-shadow: 5px 5px 5px lightcyan;
  background-color: azure;
  padding: 10px;
  border-radius: 10px;
}

.controls {
  min-width: 35%;
  max-width: 50%;
  display: flex;
  margin:1.5% auto;
  justify-content: space-around;
}

.controls button {
  width: 15%;
  border: none;
  border-radius: 20px;
  padding: 5px;
  background-color: bisque;
}

.container {
  min-width: 50%;
  max-width: 65%;
  margin: auto;
}

p {
  text-align: center;
  font-size: 2rem;
}

table {
  width:100%;
  border: 1px solid;
  border-collapse: collapse;
}

th {
  background-color: coral;
}

th, td {
  border: 1px solid;
  text-align: center;
  padding: 5px;
} 

tbody tr:nth-child(even) {
  background-color: cornflowerblue;
}
</style>
</head>
<body>
  <h1>Adding new contacts to CONTACT MANAGER using a form</h1>
  <main>
    <form onsubmit="return formSubmited();">
      <fieldset>
        <legend>Personal information</legend>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required><br>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required><br>
        <button>Add New Contact</button>
      </fieldset>
    </form>

    <section class="controls">
      <button class="save">Save</button>
      <button class="empty">Empty</button>
      <button class="load">Load</button>
    </section>

    <div class="container"></div>
  </main>
<script id="jsbin-javascript">
window.onload = init;

// The contact manager as a global variable
let cm; 

// button control
var saveBtn, emptyBtn, loadBtn;

function init() { 

  // get buttons reference 
  saveBtn = document.querySelector('.save'); 
  emptyBtn = document.querySelector('.empty'); 
  loadBtn = document.querySelector('.load');

  // listen to their click event
  saveBtn.addEventListener('click', saveData);  
  emptyBtn.addEventListener('click', eraiseData);  
  loadBtn.addEventListener('click', loadData);  

	// create an instance of the contact manager
	cm = new ContactManager();
	
  	cm.addTestData();
  	cm.printContactsToConsole();

	  // Display contacts in a table
	  // Pass the id of the HTML element that will contain the table
	  cm.displayContactsAsATable();
}

function saveData(evt) {
  cm.save();
  cm.printContactsToConsole();
}

function eraiseData(evt) {
  cm.empty();
  cm.displayContactsAsATable();
}

function loadData(evt) {
  cm.load();
  cm.displayContactsAsATable();
}

function formSubmited() {
  // Get the values from input fields
  var name = document.querySelector('#name');
  var email = document.querySelector('#email');

  // create an new contact for them
  var newContact = new Contact(name.value, email.value);

  // add the new contact to list of contact
  cm.add(newContact);

  // Empty the input fields
  name.value = '';
  email.value = '';

  // refresh the table
  cm.displayContactsAsATable();

  // do not let your browser submit the form using HTTP
  return false;
}

class Contact {
	constructor(name, email) {
		this.name = name;
		this.email = email;
	}
}

class ContactManager {
	constructor() {
		// when we build the contact manager, it
		// has an empty list of contacts
		this.listOfContacts = [];
	}

  // add some data usefull for testing
  addTestData() {
    // Generate 4 arbitrate contact
		let c1 = new Contact('Pedrito', 'Pedrito@hotmail.fr');
		let c2 = new Contact('Kader', 'Kader@hotmail.fr');
		let c3 = new Contact('Samir', 'Samir@hotmail.fr');
		let c4 = new Contact('Amin', 'Amin@hotmail.fr');
		
    // add them to list of contact
    this.add(c1);
    this.add(c2);
    this.add(c3);
    this.add(c4);
  
    // sort them by name
    this.sort();
  }
	
  // Will erase all contacts
	empty() {
		this.listOfContacts = [];
	}
	
	add(contact) {
		this.listOfContacts.push(contact);
	}
	
	remove(contact) {
		for(let i = 0; i < this.listOfContacts.length; i++) { 
			var c = this.listOfContacts[i];

			if(c.email === contact.email) {
				// remove the contact at index i
				this.listOfContacts.splice(i, i);
				// stop/exit the loop
				break;
			}
		}
	}
	
	sort() {
		// As our array contains objects, we need to pass as argument
		// a method that can compare two contacts.
		// we use for that a class method, similar to the distance(p1, p2)
		// method we saw in the ES6 Point class in module 4
		// We always call such methods using the name of the class followed
		// by the dot operator
		this.listOfContacts.sort(ContactManager.compareByName);
	}
	
	// class method for comparing two contacts by name
	static compareByName(c1, c2) {
		// JavaScript has builtin capabilities for comparing strings
		// in alphabetical order
		if (c1.name < c2.name) {
      return -1;
    }	
    if (c1.name > c2.name) {
      return 1;
    }
    return 0;
	}
	
	printContactsToConsole() {
		if(this.listOfContacts.length === 0) {
			console.log("EMPTY LIST!");
			return;
		}
		
		this.listOfContacts.forEach(function(contact) {
			console.log(contact.name);
		});
	}
	
	load() {
		if(localStorage.contacts !== undefined) {
			// the array of contacts is saved in JSON format 'String', let's convert
			// it back to a real JavaScript object.
			this.listOfContacts = JSON.parse(localStorage.contacts);
		}
	}
	
	save() {
		// We can only save strings in local Storage. So, let's convert
		// ou array of contacts to JSON
		localStorage.contacts = JSON.stringify(this.listOfContacts);
	}

  displayContactsAsATable() {
    // empty the container that contains the results
    let container = document.querySelector('.container');
    container.innerHTML = '';

		if(this.listOfContacts.length === 0) {
			container.innerHTML = '<p>No contacts to display!</p>';
			// stop the execution of this method
			return;
		}  
  
   // creates and populate the table with users
   let table = document.createElement('table');
    // create table caption
    let caption = table.createCaption();
    // set content to it
    caption.innerHTML = 'CONTACT MANAGER PROJECT';
    // create table header
    let thead = table.createTHead();
    // fill it width some content
    thead.innerHTML = '<tr>' + 
                         '<th scope="col">NAME</th>' +
                         '<th scope="col">EMAIL</th>' +
                      '</tr>';
    // create table body
    let tbody = table.createTBody();

    // create table footer
    let tfoot = table.createTFoot();
    // fill it width some content
    tfoot.innerHTML = '<tr><th colspan="2">THESE ARE OUR CUSTOMER</th></tr>';

    this.listOfContacts.forEach(function(currentContact){
      // generate a row for currentContact
      var row = tbody.insertRow();
      // currentContact is an object
      // so loop on its properties
      for (const key in currentContact) {
        if (currentContact.hasOwnProperty(key)) {
          // generate a cell for each prop of the currentContact
          const cell = row.insertCell();
          const prop = currentContact[key];
          cell.innerHTML = prop;
        }
      }
      // each iteration we add the row to the tbody
      tbody.appendChild(row);
    });  
    // finaly add table to the container
    container.appendChild(table);  
  }
}
</script>


<script id="jsbin-source-css" type="text/css">* {
  margin: 0;
  padding: 0;
  border: none;
  outline: none; 
}

body {
  font-size: 16px;
}

h1 {
  text-align: center;
  font-size: 1.5rem;
  margin: 2% 0;
}

form {
  min-width: 25%;
  max-width: 45%;
  margin: auto;
}

fieldset {
  border: 1px solid;
  padding:10px;
  border-radius:10px;
}

legend {
  text-align: center
}

label {
  width:150px;
  text-align: right;
  display:inline-block;
  margin-bottom:10px;
}

input {
  float:right;
  margin-right:70px;
  width:150px;
  padding: 3px;
  border-radius: 10px;
}

input:invalid {
  background-color:lightpink;
}

input:valid {
  background-color:lightgreen;
}

fieldset button {
  display: block;
  margin: auto;
  border: 0.5px silver solid;
  box-shadow: 5px 5px 5px lightcyan;
  background-color: azure;
  padding: 10px;
  border-radius: 10px;
}

.controls {
  min-width: 35%;
  max-width: 50%;
  display: flex;
  margin:1.5% auto;
  justify-content: space-around;
}

.controls button {
  width: 15%;
  border: none;
  border-radius: 20px;
  padding: 5px;
  background-color: bisque;
}

.container {
  min-width: 50%;
  max-width: 65%;
  margin: auto;
}

p {
  text-align: center;
  font-size: 2rem;
}

table {
  width:100%;
  border: 1px solid;
  border-collapse: collapse;
}

th {
  background-color: coral;
}

th, td {
  border: 1px solid;
  text-align: center;
  padding: 5px;
} 

tbody tr:nth-child(even) {
  background-color: cornflowerblue;
}</script>

<script id="jsbin-source-javascript" type="text/javascript">window.onload = init;

// The contact manager as a global variable
let cm; 

// button control
var saveBtn, emptyBtn, loadBtn;

function init() { 

  // get buttons reference 
  saveBtn = document.querySelector('.save'); 
  emptyBtn = document.querySelector('.empty'); 
  loadBtn = document.querySelector('.load');

  // listen to their click event
  saveBtn.addEventListener('click', saveData);  
  emptyBtn.addEventListener('click', eraiseData);  
  loadBtn.addEventListener('click', loadData);  

	// create an instance of the contact manager
	cm = new ContactManager();
	
  	cm.addTestData();
  	cm.printContactsToConsole();

	  // Display contacts in a table
	  // Pass the id of the HTML element that will contain the table
	  cm.displayContactsAsATable();
}

function saveData(evt) {
  cm.save();
  cm.printContactsToConsole();
}

function eraiseData(evt) {
  cm.empty();
  cm.displayContactsAsATable();
}

function loadData(evt) {
  cm.load();
  cm.displayContactsAsATable();
}

function formSubmited() {
  // Get the values from input fields
  var name = document.querySelector('#name');
  var email = document.querySelector('#email');

  // create an new contact for them
  var newContact = new Contact(name.value, email.value);

  // add the new contact to list of contact
  cm.add(newContact);

  // Empty the input fields
  name.value = '';
  email.value = '';

  // refresh the table
  cm.displayContactsAsATable();

  // do not let your browser submit the form using HTTP
  return false;
}

class Contact {
	constructor(name, email) {
		this.name = name;
		this.email = email;
	}
}

class ContactManager {
	constructor() {
		// when we build the contact manager, it
		// has an empty list of contacts
		this.listOfContacts = [];
	}

  // add some data usefull for testing
  addTestData() {
    // Generate 4 arbitrate contact
		let c1 = new Contact('Pedrito', 'Pedrito@hotmail.fr');
		let c2 = new Contact('Kader', 'Kader@hotmail.fr');
		let c3 = new Contact('Samir', 'Samir@hotmail.fr');
		let c4 = new Contact('Amin', 'Amin@hotmail.fr');
		
    // add them to list of contact
    this.add(c1);
    this.add(c2);
    this.add(c3);
    this.add(c4);
  
    // sort them by name
    this.sort();
  }
	
  // Will erase all contacts
	empty() {
		this.listOfContacts = [];
	}
	
	add(contact) {
		this.listOfContacts.push(contact);
	}
	
	remove(contact) {
		for(let i = 0; i < this.listOfContacts.length; i++) { 
			var c = this.listOfContacts[i];

			if(c.email === contact.email) {
				// remove the contact at index i
				this.listOfContacts.splice(i, i);
				// stop/exit the loop
				break;
			}
		}
	}
	
	sort() {
		// As our array contains objects, we need to pass as argument
		// a method that can compare two contacts.
		// we use for that a class method, similar to the distance(p1, p2)
		// method we saw in the ES6 Point class in module 4
		// We always call such methods using the name of the class followed
		// by the dot operator
		this.listOfContacts.sort(ContactManager.compareByName);
	}
	
	// class method for comparing two contacts by name
	static compareByName(c1, c2) {
		// JavaScript has builtin capabilities for comparing strings
		// in alphabetical order
		if (c1.name < c2.name) {
      return -1;
    }	
    if (c1.name > c2.name) {
      return 1;
    }
    return 0;
	}
	
	printContactsToConsole() {
		if(this.listOfContacts.length === 0) {
			console.log("EMPTY LIST!");
			return;
		}
		
		this.listOfContacts.forEach(function(contact) {
			console.log(contact.name);
		});
	}
	
	load() {
		if(localStorage.contacts !== undefined) {
			// the array of contacts is saved in JSON format 'String', let's convert
			// it back to a real JavaScript object.
			this.listOfContacts = JSON.parse(localStorage.contacts);
		}
	}
	
	save() {
		// We can only save strings in local Storage. So, let's convert
		// ou array of contacts to JSON
		localStorage.contacts = JSON.stringify(this.listOfContacts);
	}

  displayContactsAsATable() {
    // empty the container that contains the results
    let container = document.querySelector('.container');
    container.innerHTML = '';

		if(this.listOfContacts.length === 0) {
			container.innerHTML = '<p>No contacts to display!</p>';
			// stop the execution of this method
			return;
		}  
  
   // creates and populate the table with users
   let table = document.createElement('table');
    // create table caption
    let caption = table.createCaption();
    // set content to it
    caption.innerHTML = 'CONTACT MANAGER PROJECT';
    // create table header
    let thead = table.createTHead();
    // fill it width some content
    thead.innerHTML = '<tr>' + 
                         '<th scope="col">NAME</th>' +
                         '<th scope="col">EMAIL</th>' +
                      '</tr>';
    // create table body
    let tbody = table.createTBody();

    // create table footer
    let tfoot = table.createTFoot();
    // fill it width some content
    tfoot.innerHTML = '<tr><th colspan="2">THESE ARE OUR CUSTOMER</th></tr>';

    this.listOfContacts.forEach(function(currentContact){
      // generate a row for currentContact
      var row = tbody.insertRow();
      // currentContact is an object
      // so loop on its properties
      for (const key in currentContact) {
        if (currentContact.hasOwnProperty(key)) {
          // generate a cell for each prop of the currentContact
          const cell = row.insertCell();
          const prop = currentContact[key];
          cell.innerHTML = prop;
        }
      }
      // each iteration we add the row to the tbody
      tbody.appendChild(row);
    });  
    // finaly add table to the container
    container.appendChild(table);  
  }
}

</script></body>
</html>