Форум программистов, компьютерный форум, киберфорум
JavaScript
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.75/4: Рейтинг темы: голосов - 4, средняя оценка - 4.75
0 / 0 / 0
Регистрация: 04.03.2023
Сообщений: 1

Доработайте существующее приложение со списком студентов из предыдущего модуля

04.03.2023, 23:06. Показов 882. Ответов 1

Студворк — интернет-сервис помощи студентам
Добрый день. Нуждаюсь в помощи! Не могу справится с заданием.
Что нужно сделать
Доработайте существующее приложение со списком студентов из предыдущего модуля.

Добавьте возможность сохранения списка студентов на сервере. При запуске приложения должна быть выполнена проверка на наличие данных на сервере. Если данные есть, то нужно вывести список студентов на экран.

Добавьте возможность удаления студентов из списка.
JavaScript
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
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));
  }
}
HTML5
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
82
83
84
85
86
87
88
89
<!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="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <link rel="stylesheet" href="./css/normalize.css">
    <link rel="stylesheet" href="./css/style.css">
    <script defer src="./js/main.js"></script>
    <title>Студенты</title>
</head>
 
<body>
    <h1 class="h1">Студенты</h1>
    <h2 class="h2">Добавить студента</h2>
    <form class="form form-add ">
        <fieldset class="form__section">
            <label for="input__name">ФИО</label>
            <input type="text" class="form-control form-control-sm" id="input__name" name="input__name"
                placeholder="ФИО" />
        </fieldset>
        <fieldset class="form__section">
            <label for="input__faculty">Факультет</label>
            <input type="text" class="form-control form-control-sm" id="input__faculty" name="input__faculty"
                />
        </fieldset>
        <fieldset class="form__section">
            <label for="input__age">Дата рождения</label>
            <input type="date" class="form-control form-control-sm" id="input__age" name="input__age" min="1900-01-01">
        </fieldset>
        <fieldset class="form__section">
            <label for="input__start-education">Год начала обучения</label>
            <input type="number" class="form-control form-control-sm" id="input__start-education"
                name="input__start-education" placeholder="2000">
        </fieldset>
        <button type="submit" class="btn" id="btn-submit">Добавить
            студента</button>
    </form>
    <h2 class="h2">Поиск студентов</h2>
    <form class="form form-inline">
        <div class="form__search-input">
            <label for="search-name">по ФИО</label>
            <input type="text" class="form-control form-control-input" id="name">
        </div>
        <div class="form__search-input">
            <label for="search-faculty">по названию факультета</label>
            <input type="text" class="form-control form-control-input" id="faculty" name="search-faculty">
        </div>
        <div class="form__search-input">
            <label for="search-start-education">по году начала обучения</label>
            <input type="number" class="form-control form-control-input" id="startEducation"
                name="search-start-education">
        </div>
        <div class="form__search-input">
            <label for="search-finish-education">по году окончания обучения</label>
            <input type="number" class="form-control form-control-input" id="finishEducation"
                name="search-finish-education">
        </div>
    </form>
    <table class="table table">
        <thead>
            <tr>
                <th><button class="table__th-button table__th-button-name" type="button">ФИО студента</button>
                </th>
                <th><button class="table__th-button table__th-button-faculty" type="button">Факультет</button>
                </th>
                <th><button class="table__th-button table__th-button-birth" type="button">Дата рождения и
                        возраст</button></th>
                <th><button class="table__th-button table__th-button-education" type="button">Годы
                        обучения</button></th>
            </tr>
        </thead>
        <tbody id="tbody">
        </tbody>
        <tfoot>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </tfoot>
    </table>
</body>
 
</html>
CSS
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
.h1 {
    margin-bottom: 15px;
    padding-top: 15px;
    text-align: center;
}
 
.h2 {
    margin-bottom: 15px;
    text-align: center;
}
 
.form-add {
    margin: 0 auto;
    margin-bottom: 30px;
    width: 71.8%;
}
 
.form__section {
    display: inline-block;
    width: calc((100% - 15px) / 4);
}
 
.btn {
    display: block;
    margin: 0 auto;
    background-color: lightgray;
}
 
.table td,
.table th {
    padding-left: 60px;
}
 
.form-inline {
    justify-content: space-between;
    margin: 0 auto;
    margin-bottom: 15px;
    width: 70%;
}
 
.form__search-input {
    display: block;
}
 
.form-inline label {
    display: block;
}
 
.form-inline .form-control {
    width: 100%;
}
 
.table__th-button {
    padding: 8px;
    padding-right: 15px;
    border: none;
    color: black;
    background-color: transparent;
    cursor: pointer;
}
 
.table__th-button:focus {
    outline: none;
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
04.03.2023, 23:06
Ответы с готовыми решениями:

Доработайте существующее приложение со списком студентов из предыдущего модуля
Доброго времени суток! Столкнулся с заданием на курсах и как-то затупил, а курсы нужно закончить как можно скорее. Доработайте...

Работа со списком студентов (оконное приложение)
Решить задачу без двумерного массива использовать Лист Боксы и Батон клик. Желательно прикрепить файл решения. И так же если возможно код с...

Доработайте программу. Вывести на экран результирующую таблицу студентов
VV. Дан массив студентов ВУЗа: ФИО, возраст, регион, факультет. Вывести на экран результирующую таблицу: регион, количество студентов из...

1
Эксперт JSЭксперт HTML/CSS
 Аватар для krvsa
3809 / 1647 / 428
Регистрация: 14.03.2022
Сообщений: 4,099
05.03.2023, 10:45
Цитата Сообщение от AlexanderT1986 Посмотреть сообщение
Не могу справится с заданием.
Что нужно сделать
Прочитать любую книжку типа вот этой.
https://linux-doc.ru/webrtc/la... n_2014.pdf

Там будут все ответы на твои вопросы.

Вот книжка посвежее...
https://obuchalka.org/20210628... -2021.html
Миниатюры
Доработайте существующее приложение со списком студентов из предыдущего модуля  
Изображения
 
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
05.03.2023, 10:45
Помогаю со студенческими работами здесь

Выбор значения из поля со списком, исходя из предыдущего поля со списком
Дана БД. Форма на добавление данных. Необходимо сделать следующее: 1) В поле &quot;Свободно велосипедов&quot; выводить значение из...

В строках файла записаны фамилии и даты рождения студентов. Создать файл со списком несовершеннолетних студентов
В строках файла записаны фамилии и даты рождения студентов (например, Титов – 03.05.2002). Создать файл со списком несовершеннолетних...

Создать файл со списком студентов и вывести на экран студентов мужского пола, рожденных после 1998
Нужно создать файл stud со списками студентов(Имя,пол,дата рождения).С помощью созданного файла stud нужно вывести на экран студентов...

В строках файла записаны фамилии и даты рождения студентов. Создать файл со списком несовершеннолетних студентов
В строках файла записаны фамилии и даты рождения студентов(например, Попов - 03.10.2003). Создать файл со списком несовершеннолетних...

Добавление новых таблиц в существующее приложение
Доброго времени суток. При добавление новой таблицы в существующее приложение, существующей базы данных SQlLite, когда происходит...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru