Contact book using JS and LocalStorage

Simple contact book with JavaScript and LocalStorage

·

4 min read

Hi!

In this post I will create contacts book. Our book will have option to add new contact and delete it. Also our contacts are going to be stored in LocalStorage.

HTML

Here I will need 4 inputs, button to submit and also table to display our contacts.

<h1>Simple contacts book</h1>
  <div class="add-contact-wrap">
    <div class="col">
      <input type="text" id="name" placeholder="Name">
      <input type="text" id="lastname" placeholder="Last name">
      <input type="number" id="phone" placeholder="Phone">
      <input type="text" id="email" placeholder="E-mail">
    </div>
    <input type="submit" onclick="saveNewContact()">
  </div>

  <table id="tableofcontacts">
    <tr>
      <th>Name</th>
      <th>Last Name</th>
      <th>Phone</th>
      <th>E-mail</th>
      <th></th>
    </tr>
    <tr>
      <td>Maria</td>
      <td>Anders</td>
      <td>789 456 123</td>
      <td>maria@test.com</td>
      <td>
        <button class="delete-btn">delete</button>
      </td>
    </tr>
  </table>

CSS

Now we can style our HTML so it will look a bit better.

input[type='text'], input[type='number']{
  padding: 10px;
  margin-bottom: 10px;
  max-width: 250px;
}
input[type='submit']{
  border: none;
  padding: 10px 30px;
  max-width: 150px;
  cursor: pointer;
  font-family: arial, sans-serif;
  font-weight: 900;
}
.delete-btn{
  border: none;
  padding: 5px 20px;
  background-color: rgb(180, 90, 90);
  cursor: pointer;
}
.add-contact-wrap{
  display: flex;
  flex-direction: column;
}
h1{
  font-family: arial, sans-serif;;
}
table {
  margin-top: 30px;
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

At this point our app should look like this.

simplecontactsbook.PNG

JavaScript

For creating my contact details I wanted to use object. So for this I created a class named person. We will build constructor so our person class will have attributes as name, lastname, phone, email.

Person class

class Person {

  constructor(name, lastname, phone, email){
    this.name = name
    this.lastname = lastname
    this.phone = phone
    this.email = email
  }
}

saveNewContact()

First I will need all input values from our inputs. To avoid storing empty objects here I used validateInputs() function that I will create next. For saving my contacts I will use array of objects stored in LocalStorage. I create new Person object with all values from inputs. Next I push my contact to my array and save whole array to LocalStorage.

Later I will create function to display our contacts displayContacts() and to clear inputs clearInputs().

let name_input = document.getElementById('name')
let lastname_input = document.getElementById('lastname')
let phone_input = document.getElementById('phone')
let email_input = document.getElementById('email')
var contacts = []

function saveNewContact(){
  if(validateInputs() != true) return
  let new_contanct = new Person(
    name_input.value, 
    lastname_input.value, 
    phone_input.value, 
    email_input.value
  )
  contacts.push(new_contanct)
  localStorage.setItem('contacts', JSON.stringify(contacts))
  displayContacts()
  clearInputs()
}

validateInputs()

In this function I will only check if inputs are not empty and show an alert if something is empty. If everything is filled our function will return true.

function validateInputs(){
  if(name_input.value.length == 0) return alert("type name!")
  if(lastname_input.value.length == 0) return alert("type last name!")
  if(phone_input.value.length == 0) return alert("type phone!")
  if(email_input.value.length == 0) return alert("type email!")
  return true
}

clearInputs()

Here also it is quite simple, we just assing empty string as a value to our inputs.

function clearInputs(){
  name_input.value = ''
  lastname_input.value = ''
  phone_input.value = ''
  email_input.value = ''
}

displayContacts()

First thing that we need to do is to check if in our LocalStorage we already have our contacts. Because on the first app run this will be empty and our app will not work properly.

Next we create same markup as we had in our HTML. So we create variable with HTML code to store our titles. Next we save our array from LocalStorage to local variable. Now we are able to iterate through contacts array and display our contacts.

Here I added also ids to our delete buttons, this will be useful for deleting contacts. Finally inside our table we can display our contacts.

function displayContacts(){
  if(localStorage.getItem('contacts') == null) return
  let html = `
    <tr>
        <th>Name</th>
        <th>Last Name</th>
        <th>Phone</th>
        <th>E-mail</th>
        <th> </th>
    </tr>`
  contacts = JSON.parse(localStorage.getItem('contacts'))
  let id = 0
  for( let contact of contacts) {
    let person = `
    <tr>
      <td>${contact.name}</td>
      <td>${contact.lastname}</td>
      <td>${contact.phone}</td>
      <td>${contact.email}</td>
      <td>
        <button id="${id}" class="delete-btn" onclick="removeItem(this.id)">delete</button>
      </td>
    </tr>`
    html += person
    id++
  }
  id = 0
  table.innerHTML = html
}
displayContacts()

removeItem()

For removing an item we can create function that as a parameter gets clicked id. We once more get our contacts array from LocalStorage. Next we remove element from array same as our clicked id.

Finally we can save our changed array and displayContacts once again.

function removeItem(clicked_id){
  contacts = JSON.parse(localStorage.getItem('contacts'))
  contacts.splice(clicked_id, 1)
  localStorage.setItem('contacts', JSON.stringify(contacts))
  displayContacts()
}

Nowe we should have working contacts book :)

If you find any mistakes or you have ideas how to refactor my solutions to be simplier/ better please let me know :)

Did you find this article valuable?

Support knowledge blog by becoming a sponsor. Any amount is appreciated!