Files
Project/main.js

76 lines
3.5 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
const newProjectForm = document.getElementById('new-project-form');
const tableBody = document.querySelector('.table tbody');
newProjectForm.addEventListener('submit', (event) => {
event.preventDefault();
const roomNumber = document.getElementById('room-number').value;
const roomType = document.getElementById('room-type').value;
const rate = parseFloat(document.getElementById('rate').value);
const guestName = document.getElementById('guest-name').value;
const guestPhone = document.getElementById('guest-phone').value;
const checkInDate = document.getElementById('check-in-date').value;
const checkOutDate = document.getElementById('check-out-date').value;
try {
// Input Validation (Crucial for robust code)
if (!roomNumber || !roomType || isNaN(rate) || !guestName || !guestPhone || !checkInDate || !checkOutDate) {
throw new Error("Пожалуйста, заполните все поля корректно.");
}
const newRow = document.createElement('tr');
const roomNumberCell = document.createElement('td');
roomNumberCell.textContent = roomNumber;
const roomTypeCell = document.createElement('td');
roomTypeCell.textContent = roomType;
const rateCell = document.createElement('td');
rateCell.textContent = rate.toFixed(2);
const availabilityCell = document.createElement('td');
availabilityCell.textContent = 'Доступен';
const guestNameCell = document.createElement('td');
guestNameCell.textContent = guestName;
const guestPhoneCell = document.createElement('td');
guestPhoneCell.textContent = guestPhone;
const datesCell = document.createElement('td');
datesCell.textContent = `${checkInDate} - ${checkOutDate}`; // Correct template literal
const costCell = document.createElement('td');
const checkInDateObj = new Date(checkInDate);
const checkOutDateObj = new Date(checkOutDate);
const timeDiff = checkOutDateObj.getTime() - checkInDateObj.getTime();
const numNights = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (isNaN(numNights) || numNights < 0) {
throw new Error("Неверные даты. Убедитесь, что дата выезда позже даты заезда.");
}
const cost = numNights * rate;
costCell.textContent = cost.toFixed(2);
newRow.appendChild(roomNumberCell);
newRow.appendChild(roomTypeCell);
newRow.appendChild(rateCell);
newRow.appendChild(availabilityCell);
newRow.appendChild(guestNameCell);
newRow.appendChild(guestPhoneCell);
newRow.appendChild(datesCell);
newRow.appendChild(costCell);
tableBody.appendChild(newRow);
newProjectForm.reset();
} catch (error) {
console.error("Произошла ошибка:", error);
alert("Произошла ошибка при обработке данных: " + error.message + ". Пожалуйста, проверьте введенные данные."); // Show error message to user
}
});
});