Помогите с написанием кода.
Имеется "приложение" таблица студентов.
По заданию необходимо:
1. Добавлять студентов на сервер (fetch(
http://localhost:3000/api/students/ method: 'POST') - выполнил
2. При запуске приложения должен выводится список студентов на экран. - выполнил
3.Добавить кнопку "Удалить"(добавил), которая по нажатию будет удалять объект(студента) из базы и строку из таблицы (fetch(http://localhost:3000/api/students/{id} method: 'Delete').
Нужно реализовать удаления, а я не могу сообразить как это выполнить. Буду благодарен, если кто-нибудь поможет! {id} создается автоматически
В базу элементы добавляются в следующем виде:
[{"name":"Дмитрий","surname":"Старцев ","lastname":"Викторович","birthday":"Su n May 18 1986 06:00:00 GMT+0600 (Екатеринбург, летнее время)","studyStart":"2019","faculty":"Эле ктротехнический","id":"167818993780 1","updatedAt":"2023-03-07T11:52:17.801Z","createdAt":"2023-03-07T11:52:17.801Z"}]
document.addEventListener('DOMContentLoaded', async () => {
async function getStudents() {
const response = await fetch(`http://localhost:3000/api/students`);
const data = await response.json();
return data;
}
let objectsStudents = await getStudents();
function createRow() {
const container = document.getElementById('tbody');
const row = document.createElement('tr');
const td1 = document.createElement('td');
const td2 = document.createElement('td');
const td3 = document.createElement('td');
const td4 = document.createElement('td');
let deleteButton = document.createElement('button');
deleteButton.classList.add('btn', 'btn-danger');
deleteButton.textContent = 'Удалить';
row.append(td1);
row.append(td2);
row.append(td3);
row.append(td4);
row.append(deleteButton);
container.append(row);
return { row, td1, td2, td3, td4, deleteButton };
}
function createStudent(array) {
document.getElementById('tbody').innerHTML = '';
for (let i = 0; i < array.length; i++) {
const now = new Date();
const addRow = createRow();
const finishEducation = Number(array[i].studyStart) + Number(4);
const course = now.getFullYear() - Number(array[i].studyStart);
addRow.td1.innerHTML = array[i].surname + ' ' + array[i].name + ' ' + array[i].lastname;
addRow.td2.innerHTML = array[i].faculty;
let date = new Date(array[i].birthday).getDate();
if (date < 10) date = '0' + date;
let month = new Date(array[i].birthday).getMonth() + 1;
if (month < 10) month = '0' + month;
const year = new Date(array[i].birthday).getFullYear();
const born = new Date(year, month, date);
const getAge = Math.floor((now.getTime() - born.getTime()) / 1000 / 60 / 60 / 24 / 365.25);
addRow.td3.innerHTML = date + '.' + month + '.' + year + ' ( ' + getAge + ' лет ) ';
addRow.td4.innerHTML = Number(array[i].studyStart) + ' - ' + finishEducation + ' ( ' + course + ' курс ) ';
if (course >= 5) {
addRow.td4.innerHTML = 'закончил';
}
}
return array;
}
createStudent(objectsStudents);
const newArray = objectsStudents.slice();
document.querySelector('.table__th-button-name').addEventListener('click', function () {
const result = newArray.sort((a, b) => (a.surname > b.surname ? 1 : -1));
createStudent(result);
});
document.querySelector('.table__th-button-faculty').addEventListener('click', function () {
const result = newArray.sort((a, b) => (a.faculty > b.faculty ? 1 : -1));
createStudent(result);
});
document.querySelector('.table__th-button-birth').addEventListener('click', function () {
const result = newArray.sort((a, b) => (a.birthday < b.birthday ? 1 : -1));
createStudent(result);
});
document.querySelector('.table__th-button-education').addEventListener('click', function () {
const result = newArray.sort((a, b) =>
(a.studyStart < b.studyStart ? 1 : -1));
createStudent(result);
});
const form = document.querySelector('.form-add');
const fields = form.querySelectorAll('.form-control');
const inputName = document.getElementById('input__name');
const inputFaculty = document.getElementById('input__faculty');
const inputBirth = document.getElementById('input__age');
const inputStartEducation = document.getElementById('input__start-education');
const date = new Date();
function showError(message) {
const error = document.createElement('div');
error.classList.add('error');
error.style.color = 'orange';
error.innerHTML = message;
return error;
}
function removeError() {
const errors = form.querySelectorAll('.error');
for (let i = 0; i < errors.length; i++) {
errors[i].remove();
}
}
form.addEventListener('submit', async function (e) {
e.preventDefault();
removeError();
function getAgeInForm(birthDate) {
const now = new Date();
const born = new Date(
birthDate.getFullYear(),
birthDate.getMonth() + 1,
birthDate.getDate(),
);
const diffInMilliseconds = now.getTime() - born.getTime();
return Math.floor(diffInMilliseconds / 1000 / 60 / 60 / 24 / 365.25);
}
function formatDateInForm(dateInForm) {
let d = dateInForm.getDate();
if (d < 10) d = '0' + d;
let m = dateInForm.getMonth() + 1;
if (m < 10) m = '0' + m;
const y = dateInForm.getFullYear();
return d + '.' + m + '.' + y;
}
for (let i = 0; i < fields.length; i++) {
if (!fields[i].value.trim() || fields[i].value.length < 3) {
const error = showError('Заполните поле');
fields[i].parentElement.insertBefore(error, fields[i]);
return;
}
}
if (inputBirth.valueAsDate > date) {
const error = showError('Введите корректную дату!');
inputBirth.parentElement.insertBefore(error, inputBirth);
return;
}
if (inputStartEducation.value !== '' && inputStartEducation.value < 2000 || inputStartEducation.value > date.getFullYear()) {
const error = showError('Не ранее 2000г, не позднее текущего года!');
inputStartEducation.parentElement.insertBefore(error, inputStartEducation);
return;
}
const addRow = createRow();
addRow.td1.innerHTML = inputName.value;
addRow.td2.innerHTML = inputFaculty.value;
addRow.td3.innerHTML = formatDateInForm(new Date(inputBirth.value)) + ' ( ' + getAgeInForm(new Date(inputBirth.value)) + ' лет ) ';
const finishEducation = Number(inputStartEducation.value) + Number(4);
const course = date.getFullYear() - Number(inputStartEducation.value) + ' курс ';
addRow.td4.innerHTML = inputStartEducation.value + ' - ' + finishEducation + ' ( ' + course + ' ) ';
if (finishEducation < date.getFullYear()) {
addRow.td4.innerHTML = 'закончил';
}
const split = inputName.value.split(' ');
const objectsStudents = {};
objectsStudents.name = split[1];
objectsStudents.surname = split[0];
objectsStudents.lastname = split[2];
objectsStudents.birthday = new Date(inputBirth.value);
objectsStudents.studyStart = inputStartEducation.value;
objectsStudents.faculty = inputFaculty.value;
inputName.value = '';
inputFaculty.value = '';
inputBirth.value = '';
inputStartEducation.value = '';
let response = await fetch(`http://localhost:3000/api/students`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: `${objectsStudents.name}`,
surname: `${objectsStudents.surname}`,
lastname: `${objectsStudents.lastname}`,
birthday: `${objectsStudents.birthday}`,
studyStart: `${objectsStudents.studyStart}`,
faculty: `${objectsStudents.faculty}`
})
});
const result = await response.json();
objectsStudents.push(result);
});
function filterName(objectsStudents, val) {
if (val !== "") {
return objectsStudents.filter(f => (f.surname + f.name + f.lastname).toLowerCase().includes(val.toLowerCase()));
} else {
return objectsStudents;
}
}
function filterFaculty(objectsStudents, val) {
if (val !== "") {
return objectsStudents.filter(f => f.faculty.toLowerCase().includes(val.toLowerCase()));
} else {
return objectsStudents;
}
}
function filterStartEducation(objectsStudents, key, val) {
if (val != "") {
return objectsStudents.filter(el => String(el[key]).toLowerCase().includes(val));
} else {
return objectsStudents;
}
}
function filterFinishEducation(objectsStudents, key, val) {
if (val != "") {
return objectsStudents.filter(el => String(el[key]).toLowerCase().includes(val));
} else {
return objectsStudents;
}
}
let idTimeout;
document.addEventListener("keyup", function (event) {
clearTimeout(idTimeout);
idTimeout = setTimeout(function () {
filterAndUpdate(event);
}, 300);
})
function filterAndUpdate(event) {
if (event.target && event.target.matches('input#name')) {
createStudent(filterName(objectsStudents, event.target.value));
}
if (event.target && event.target.matches('input#faculty')) {
createStudent(filterFaculty(objectsStudents, event.target.value));
}
if (event.target && event.target.matches('input#startEducation')) {
createStudent(filterStartEducation(objectsStudents, "studyStart", event.target.value));
}
if (event.target && event.target.matches('input#finishEducation')) {
createStudent(filterFinishEducation(objectsStudents, "finishEducation", event.target.value));
}
}
});