Добрый день. Нуждаюсь в помощи! Не могу справится с заданием.
Что нужно сделать
Доработайте существующее приложение со списком студентов из предыдущего модуля.
Добавьте возможность сохранения списка студентов на сервере. При запуске приложения должна быть выполнена проверка на наличие данных на сервере. Если данные есть, то нужно вывести список студентов на экран.
Добавьте возможность удаления студентов из списка.
let objectsStudents = [{
name: 'Александр',
surname: 'Слобожанинов',
middleName: 'Сергеевич',
birth: new Date(1984, 11, 10),
startEducation: 2019,
faculty: 'Электротехнический',
}, {
name: 'Наталья',
surname: 'Степанова',
middleName: 'Витальевна',
birth: new Date(1936, '24', '18'),
startEducation: 2021,
faculty: 'Юридический',
}];
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');
row.append(td1);
row.append(td2);
row.append(td3);
row.append(td4);
container.append(row);
return { row, td1, td2, td3, td4 };
}
if (localStorage.getItem('newArray') !== null || localStorage.getItem('newArray') !== '') {
objectsStudents = localStorage.newArray ? JSON.parse(localStorage.getItem('newArray'), function (key, value) {
if (key === 'birth') return new Date(value);
return value;
}) : objectsStudents;
}
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].startEducation) + Number(4);
const course = now.getFullYear() - Number(array[i].startEducation);
addRow.td1.innerHTML = array[i].surname + ' ' + array[i].name + ' ' + array[i].middleName;
addRow.td2.innerHTML = array[i].faculty;
let date = array[i].birth.getDate();
if (date < 10) date = '0' + date;
let month = array[i].birth.getMonth() + 1;
if (month < 10) month = '0' + month;
const year = array[i].birth.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].startEducation) + ' - ' + 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.birth < b.birth ? 1 : -1));
createStudent(result);
});
document.querySelector('.table__th-button-education').addEventListener('click', function () {
const result = newArray.sort((a, b) =>
(a.startEducation < b.startEducation ? 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();
let filterObjectsStudents;
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', 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 studentObject = {};
studentObject.name = split[1];
studentObject.surname = split[0];
studentObject.middleName = split[2];
studentObject.birth = new Date(inputBirth.value);
studentObject.startEducation = inputStartEducation.value;
studentObject.faculty = inputFaculty.value;
objectsStudents.push(studentObject);
newArray.push(studentObject);
filterObjectsStudents.push(studentObject);
localStorage.setItem('newArray', JSON.stringify(objectsStudents));
inputName.value = '';
inputFaculty.value = '';
inputBirth.value = '';
inputStartEducation.value = '';
});
filterObjectsStudents = objectsStudents.slice();
function filterName(objectsStudents, val) {
if (val !== "") {
return objectsStudents.filter(f => (f.surname + f.name + f.middleName).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] + Number(4)).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, "startEducation", event.target.value));
}
if (event.target && event.target.matches('input#finishEducation')) {
createStudent(filterFinishEducation(objectsStudents, "startEducation", event.target.value));
}
}