54 lines
1.8 KiB
JavaScript
54 lines
1.8 KiB
JavaScript
(function () {
|
|
'use strict';
|
|
|
|
function updateDepartureDate(arrivalDateField) {
|
|
const arrivalDate = new Date(arrivalDateField.value);
|
|
if (isNaN(arrivalDate.getTime())) {
|
|
return;
|
|
}
|
|
const departureDateField = document.querySelector('[name="departure_date"]');
|
|
if (!departureDateField) {
|
|
return;
|
|
}
|
|
|
|
const minNights = Math.max(1, parseInt(departureDateField.dataset.minNights, 10));
|
|
arrivalDate.setUTCDate(arrivalDate.getUTCDate() + minNights);
|
|
const minDate = formatDate(arrivalDate);
|
|
|
|
departureDateField.setAttribute('min', minDate);
|
|
const departureDate = new Date(departureDateField.value);
|
|
const validDepartureDate = !isNaN(departureDate.getTime())
|
|
if (!validDepartureDate || departureDate < arrivalDate) {
|
|
departureDateField.value = minDate;
|
|
}
|
|
|
|
const maxNights = parseInt(departureDateField.dataset.maxNights, 10);
|
|
if (maxNights > 0) {
|
|
arrivalDate.setUTCDate(arrivalDate.getUTCDate() + maxNights - minNights);
|
|
const maxDate = formatDate(arrivalDate);
|
|
departureDateField.setAttribute('max', maxDate);
|
|
if (validDepartureDate && departureDate >= arrivalDate) {
|
|
departureDateField.value = maxDate;
|
|
}
|
|
}
|
|
}
|
|
|
|
function formatDate(date) {
|
|
return `${date.getFullYear()}-${zeroPad(date.getMonth() + 1)}-${zeroPad(date.getDate())}`;
|
|
}
|
|
|
|
function zeroPad(num) {
|
|
return `${num < 10 ? '0' : ''}${num}`
|
|
}
|
|
|
|
const arrivalDateField = document.querySelector('[name="arrival_date"]');
|
|
if (!arrivalDateField) {
|
|
return;
|
|
}
|
|
arrivalDateField.addEventListener('change', function (event) {
|
|
updateDepartureDate(event.target);
|
|
});
|
|
|
|
updateDepartureDate(arrivalDateField);
|
|
})();
|