phone-book/public/script.js
2025-03-10 22:18:45 +03:00

52 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

document.addEventListener('DOMContentLoaded', async () => {
const searchInput = document.getElementById('searchInput');
const contactsList = document.getElementById('contactsList');
const noResults = document.querySelector('.no-results');
let contacts = [];
// Загрузка данных с сервера
try {
const response = await fetch('/api/contacts');
contacts = await response.json();
renderContacts(contacts);
} catch (error) {
console.error('Ошибка при загрузке контактов:', error);
noResults.textContent = 'Ошибка при загрузке контактов';
noResults.style.display = 'block';
}
function formatPhoneNumbers(phone) {
if (!phone || phone === '-') return '-';
return phone.split(';').map(num => num.trim()).filter(Boolean).join('\n');
}
function renderContacts(contactsToRender) {
contactsList.innerHTML = contactsToRender.map(contact => `
<tr>
<td>${contact.name}</td>
<td>${contact.title}</td>
<td>${contact.department}</td>
<td>${formatPhoneNumbers(contact.phone)}</td>
<td>${contact.email}</td>
</tr>
`).join('');
}
function filterContacts(searchTerm) {
searchTerm = searchTerm.toLowerCase();
const filteredContacts = contacts.filter(contact =>
contact.name.toLowerCase().includes(searchTerm) ||
contact.title.toLowerCase().includes(searchTerm) ||
contact.department.toLowerCase().includes(searchTerm) ||
(contact.phone && contact.phone !== '-' && contact.phone.toLowerCase().includes(searchTerm)) ||
(contact.email && contact.email !== '-' && contact.email.toLowerCase().includes(searchTerm))
);
renderContacts(filteredContacts);
noResults.style.display = filteredContacts.length ? 'none' : 'block';
}
searchInput.addEventListener('input', (e) => {
filterContacts(e.target.value);
});
});