Как можно настроить фильтрацию по году окончания обучения?
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/bootstrap.css">
<title>Document</title>
</head>
<body>
<div class="container">
<form id="addStudent" action="#">
<div class="row">
<label class="col-6 mb-2"> Фамилия
<input id="input-sureName" class="form-control" type="text" tabindex="1">
</label>
<label class="col-6 mb-2"> Факультет
<input id="input-faculty" class="form-control" type="text" tabindex="4">
</label>
<label class="col-6 mb-2"> Имя
<input id="input-name" class="form-control" type="text" tabindex="2">
</label>
<label class="col-6 mb-2"> Дата рождения
<input id="input-birthday" class="form-control" type="date" tabindex="5">
</label>
<label class="col-6 mb-2"> Отчество
<input id="input-middleName" class="form-control" type="text" tabindex="3">
</label>
<label class="col-6 mb-2"> Год поступления
<input id="input-startTraining" class="form-control" type="number " min="2000" tabindex="6">
</label>
<div class="btn-group mb-5">
<button class="btn btn-primary" type="submit">Добавить</button>
<button class="btn btn-secondary" type="reset">Очистить</button>
</div>
</div>
</form>
<form class="row" id="filter-form" action="#" class="" id="filter">
<span>Поиск по таблице</span>
<div class="col">
<input class="form-control" id="filter-fio" type="text" placeholder="ФИО">
</div>
<div class="col">
<input class="form-control" id="filter-faculty" type="text" placeholder="Факультет">
</div>
<div class="col">
<input class="form-control" id="filter-teachStart" type="number" placeholder="Год начала обучения">
</div>
<div class="col">
<input class="form-control" id="filter-teachFinish" type="number" placeholder="Год окончания обучения">
</div>
<div class="col">
<button class="btn btn-primary" id="filterBtn" type="submit">Найти</button>
</div>
</form>
<table class="table">
<thead>
<tr id="studentsListTR">
<th data-column="fullName" scope="col">ФИО</th>
<th data-column="birthday" scope="col">Дата рождения</th>
<th data-column="faculty" scope="col">Факультет</th>
<th data-column="teachStart" scope="col">Годы обучения</th>
</tr>
</thead>
<tbody id="students-list">
</tbody>
</table>
</div>
[JS]// массив студентов
let studentsList = [
{name: "Владимир",
middleName: "Николавеич",
sureName: "Кубанов",
fullName: "Кубанов Владимир Николавеич",
teachStart: 2012,
faculty: "Юридический",
birthday: new Date(1994, 6, 9),
},
{name: "Петр",
middleName: "Владимирович",
sureName: "Смирнов",
fullName: "Смирнов Петр Владимирович",
teachStart: 2018,
faculty: "Исторический",
birthday: new Date(1993, 10, 25),
},
{name: "Игорь",
middleName: "Борисович",
sureName: "Мельников",
fullName: "Мельников Игорь Борисович",
teachStart: 2020,
faculty: "Юридический",
birthday: new Date(2000, 3, 9),
},
{name: "Иван",
middleName: "Иванович",
sureName: "Иванов",
fullName: "Иванов Иван Иванович",
teachStart: 2004,
faculty: "Исторический",
birthday: new Date(1988, 11, 25),
},
];
const $studentsListTable = document.getElementById('studentsListTR'),
$studentsListTH = document.querySelectorAll('th');
// Соединяем ФИО
function getFullName(name, middleName, sureName ) {
const fullName = sureName + ' ' + name + ' ' + middleName;
return fullName;
};
// Исправляем формат даты рождения
function getBirthday(dateBirthday) {
let birthday = dateBirthday.toISOString().split('T')[0].split('-');
let correctBirthday = birthday[2] + '.' + birthday[1] + '.' + birthday[0];
return correctBirthday;
};
function getAge(correctBirthday) {
return ` (${((new Date() - new Date(correctBirthday)) / (24 * 3600 * 365.25 * 1000)) | 0 } лет)`;
};
// считаем закончил ли учиться или на каком курсе учится
function getStudyTime(startTraining) {
let currentTime = new Date();
if ((currentTime.getMonth() + 1 >= 9 && (currentTime.getFullYear() - startTraining > 4)) || (currentTime.getFullYear() - startTraining > 4) ) {
return `${+startTraining} - ${+startTraining + 4} (закончил)`;
} else {
return `${+startTraining} - ${+startTraining + 4} (${currentTime.getFullYear() - startTraining}-й курс)`;
}
};
// получаем таблицу студентов
const $students_list = document.getElementById('students-list')
function newStudentTR(student) {
const $studentTR = document.createElement('tr'),
$fioTD = document.createElement('td'),
$birthdayTD = document.createElement('td'),
$facultyTD = document.createElement('td'),
$teachStartTD = document.createElement('td')
$fioTD.textContent = student['fullName']
$birthdayTD.textContent = getBirthday(student['birthday']) + getAge(student['birthday']);
$facultyTD.textContent = student['faculty'];
$teachStartTD.textContent = getStudyTime(student['teachStart']);
$studentTR.append($fioTD);
$studentTR.append($birthdayTD);
$studentTR.append($facultyTD);
$studentTR.append($teachStartTD);
return $studentTR;
};
function getFilterInput() {
const inputFioValueFilter = document.getElementById('filter-fio').value.toLowerCase().trim();
const inputFacultyValueFilter = document.getElementById('filter-faculty').value.toLowerCase().trim();
const inputTeachStartValueFilter = document.getElementById('filter-teachStart').value.trim();
const inputteachFinishValueFilter = document.getElementById('filter-teachFinish').value.trim();
return {
inputFioValueFilter,
inputteachFinishValueFilter,
inputFacultyValueFilter,
inputTeachStartValueFilter
}
}
// сортировка столбцов таблицы по параметрам
let column = '',
columnDir = true;
function sortedUsersList(arr, prop, dir) {
const studentsListCopy = [...arr];
return studentsListCopy.sort( (studentA,studentB) => {
if (!dir ? studentA[prop] < studentB[prop] : studentA[prop] > studentB[prop])
return -1;
});
}
// фильтрация таблицы
function filterUsersList(arr, prop, value) {
let resultFilter = [];
let studentsListCopy = [...arr];
for (let item of studentsListCopy) {
if (String(item[prop]).toLowerCase().includes(String(value))) {
resultFilter.push(item);
}
}
return resultFilter
}
// отрисовка таблицы
function render(arr) {
let studentsListCopy = [...arr];
studentsListCopy = sortedUsersList(studentsList, column, columnDir);
studentsListCopy = filterUsersList(studentsListCopy, 'fullName', getFilterInput().inputFioValueFilter)
studentsListCopy = filterUsersList(studentsListCopy, 'faculty', getFilterInput().inputFacultyValueFilter)
studentsListCopy = filterUsersList(studentsListCopy, 'teachStart', getFilterInput().inputTeachStartValueFilter)
studentsListCopy = filterUsersList(studentsListCopy, 'teachStart', getFilterInput().inputteachFinishValueFilter)
$students_list.innerHTML = '';
for (const student of studentsListCopy) {
$students_list.append(newStudentTR(student));
}
};
// получаем данные из формы
document.getElementById('addStudent').addEventListener('submit', function(event) {
event.preventDefault();
let newStudent = {
name: document.getElementById('input-name').value,
middleName: document.getElementById('input-middleName'),
sureName: document.getElementById('input-sureName').value,
fullName: getFullName(document.getElementById('input-sureName').value, document.getElementById('input-name').value, document.getElementById('input-middleName').value),
teachStart: document.getElementById('input-startTraining').value,
faculty: document.getElementById('input-faculty').value,
birthday: new Date(document.getElementById('input-birthday').value),
};
console.log(new Date(document.getElementById('input-birthday').value));
studentsList.push(newStudent);
render(studentsList);
})
// события клика по заголовкам таблицы для сортировки
$studentsListTH.forEach(element => {
element.addEventListener('click', function () {
column = this.dataset.column;
columnDir = !columnDir
render(studentsList);
})
})
// события кнопик фильтрации
document.getElementById('filter-form').addEventListener('submit', function (event) {
event.preventDefault();
render(studentsList)
})
render(studentsList);[/JS]
</body>
</html>