This repository has been archived by the owner on Jul 6, 2024. It is now read-only.
forked from mhaidarhanif/address-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (62 loc) · 2.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const searchInputElement = document.getElementById("search-input");
const addContactFormElement = document.getElementById("add-contact-form");
const contactsContainerElement = document.getElementById("contacts-container");
function searchContacts(contacts, keyword) {
searchInputElement.value = keyword;
const filteredContacts = contacts.filter((contact) =>
contact.fullName.toLowerCase().includes(keyword.toLowerCase())
);
return filteredContacts;
}
function renderContacts() {
const contacts = loadContacts();
const queryString = window.location.search;
const params = new URLSearchParams(queryString);
const keyword = params.get("q");
const contactsToRender = keyword
? searchContacts(contacts, keyword)
: contacts;
const contactItemElements = contactsToRender.map(
(contact) => `<li>
<a href="/contact/?id=${contact.id}">
<h2>${contact.fullName}</h2>
<p>${contact.email}</p>
<p>${contact.phone}</p>
</a>
<div>
<button onclick="deleteContactById(${contact.id})">Delete</button>
</div>
</li>
`
);
const contactItems = contactItemElements.join("");
contactsContainerElement.innerHTML = contactItems;
}
function addContact(event) {
event.preventDefault();
const contactFormData = new FormData(addContactFormElement);
const contacts = loadContacts();
const newId = contacts.length ? contacts[contacts.length - 1].id + 1 : 1;
const newContact = {
id: newId,
fullName: contactFormData.get("fullName"),
email: contactFormData.get("email"),
phone: contactFormData.get("phone"),
age: Number(contactFormData.get("age")),
};
// Update by adding a new object in the array
const updatedContacts = [...contacts, newContact];
saveContacts(updatedContacts);
addContactFormElement.reset();
renderContacts();
}
function deleteContactById(id) {
const contacts = loadContacts();
const updatedContacts = contacts.filter(
(contact) => contact.id !== Number(id)
);
saveContacts(updatedContacts);
renderContacts();
}
addContactFormElement.addEventListener("submit", addContact);
window.addEventListener("load", renderContacts);