Advertisement
KAMEN1973

3 Phonebook

Jul 6th, 2020
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     console.log('TODO...');
  3.  
  4.     const inputName = document.querySelector('#person');
  5.     const inputPhone = document.querySelector('#phone');
  6.     const btnCreate = document.querySelector('#btnCreate');
  7.     const btnLoad = document.querySelector('#btnLoad');
  8.     const ulPhonebook = document.querySelector('#phonebook');
  9.  
  10.     let baseURL = 'http://localhost:3000/phonebook';
  11.     let contacts = [];
  12.  
  13.     btnCreate.addEventListener('click', onClickCreate);
  14.     btnLoad.addEventListener('click', onClickLoad);
  15.  
  16.     function onClickCreate(e) {
  17.         if (inputName.value !== '' && inputPhone.value !== '') {
  18.  
  19.             let newContact = {
  20.                 name: inputName.value,
  21.                 phone: inputPhone.value
  22.             };
  23.  
  24.             fetch(baseURL, {
  25.                 method: 'POST',
  26.                 body: JSON.stringify(newContact)
  27.             })
  28.                 .then(response => response.json())
  29.                 .then(result => contacts.push(result));
  30.  
  31.  
  32.             inputName.value = '';
  33.             inputPhone.value = '';
  34.         }
  35.     }
  36.  
  37.     function onClickLoad(e) {
  38.         Array.from(ulPhonebook.querySelectorAll('li')).map(x => x.remove());
  39.        
  40.         contacts.forEach(contact => {
  41.             let btnDelete = document.createElement('button');
  42.             btnDelete.textContent = 'Delete';
  43.             //console.log(Object.keys(contact)[0]);
  44.             let key = Object.keys(contact)[0];
  45.  
  46.             let li = document.createElement('li');
  47.             li.textContent = `${contact[key].name}: ${contact[key].phone}`;
  48.             li.appendChild(btnDelete);
  49.  
  50.             ulPhonebook.appendChild(li);
  51.  
  52.             btnDelete.addEventListener('click', (e) => {
  53.                 let li = e.target.parentElement;
  54.  
  55.                 let getContact = contacts.find(x => li.textContent.includes(Object.values(x)[0].phone));
  56.                 contacts.splice(contacts.indexOf(getContact), 1);
  57.  
  58.                 li.remove();
  59.             });
  60.         });
  61.     }
  62.  
  63. }
  64.  
  65. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement