|
| 1 | +const formRef = document.querySelector('form'); |
| 2 | +const getInputRef = (name) => formRef.querySelector(`[name="${name}"]`); |
| 3 | + |
| 4 | +export const StudentForm = { |
| 5 | + get formData() { |
| 6 | + return new FormData(formRef); |
| 7 | + }, |
| 8 | + |
| 9 | + get data() { |
| 10 | + return { |
| 11 | + name: this.formData.get('name'), |
| 12 | + surname: this.formData.get('surname'), |
| 13 | + birthday: this.formData.get('birthday'), |
| 14 | + }; |
| 15 | + }, |
| 16 | + |
| 17 | + set data({ name, surname, birthday }) { |
| 18 | + getInputRef('name').value = name; |
| 19 | + getInputRef('surname').value = surname; |
| 20 | + getInputRef('birthday').value = birthday; |
| 21 | + }, |
| 22 | + |
| 23 | + get age() { |
| 24 | + const birthDate = this.data.birthday; |
| 25 | + const currentDate = new Date(); |
| 26 | + const [currentYear, currentMonth, currentDay] = [ |
| 27 | + currentDate.getFullYear(), |
| 28 | + currentDate.getMonth(), |
| 29 | + currentDate.getDate(), |
| 30 | + ]; |
| 31 | + const [birthYear, birthMonth, birthDay] = birthDate.split('-').map((item) => +item); |
| 32 | + let calculatedAge = currentYear - birthYear; |
| 33 | + |
| 34 | + if (currentMonth < birthMonth - 1) calculatedAge--; |
| 35 | + |
| 36 | + if (birthMonth - 1 === currentMonth && currentDay < birthDay) calculatedAge--; |
| 37 | + |
| 38 | + return calculatedAge; |
| 39 | + }, |
| 40 | + |
| 41 | + onChange(action) { |
| 42 | + formRef.addEventListener('input', () => action(this.data)); |
| 43 | + }, |
| 44 | + |
| 45 | + onSubmit(action) { |
| 46 | + formRef.addEventListener('submit', (event) => { |
| 47 | + event.preventDefault(); |
| 48 | + action(); |
| 49 | + }); |
| 50 | + }, |
| 51 | +}; |
0 commit comments