Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- console.log('TODO...');
- const inputName = document.querySelector('#person');
- const inputPhone = document.querySelector('#phone');
- const btnCreate = document.querySelector('#btnCreate');
- const btnLoad = document.querySelector('#btnLoad');
- const ulPhonebook = document.querySelector('#phonebook');
- let baseURL = 'http://localhost:3000/phonebook';
- let contacts = [];
- btnCreate.addEventListener('click', onClickCreate);
- btnLoad.addEventListener('click', onClickLoad);
- function onClickCreate(e) {
- if (inputName.value !== '' && inputPhone.value !== '') {
- let newContact = {
- name: inputName.value,
- phone: inputPhone.value
- };
- fetch(baseURL, {
- method: 'POST',
- body: JSON.stringify(newContact)
- })
- .then(response => response.json())
- .then(result => contacts.push(result));
- inputName.value = '';
- inputPhone.value = '';
- }
- }
- function onClickLoad(e) {
- Array.from(ulPhonebook.querySelectorAll('li')).map(x => x.remove());
- contacts.forEach(contact => {
- let btnDelete = document.createElement('button');
- btnDelete.textContent = 'Delete';
- //console.log(Object.keys(contact)[0]);
- let key = Object.keys(contact)[0];
- let li = document.createElement('li');
- li.textContent = `${contact[key].name}: ${contact[key].phone}`;
- li.appendChild(btnDelete);
- ulPhonebook.appendChild(li);
- btnDelete.addEventListener('click', (e) => {
- let li = e.target.parentElement;
- let getContact = contacts.find(x => li.textContent.includes(Object.values(x)[0].phone));
- contacts.splice(contacts.indexOf(getContact), 1);
- li.remove();
- });
- });
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement