Replies: 1
I attempted to create a custom JavaScript function to control the time field. This condition checks whether the selected date is today. If it is, the available hours will be limited to the remaining hours of the day. For example, if today’s date is selected and the current time is 15:00, only time slots after 17:00 will be displayed.
Here is the code I created:
// Function to filter available time options based on the current time
function updateTimeOptions() {
var dateInput = $('input[name="date-1"]').val(); // Get the value from the date input field
var hoursSelect = $('select[name="time-2-hours"]'); // The hours dropdown
var serverTime = new Date(ajax_object.server_time); // Get the server time passed from PHP
if (!dateInput) return; // Stop if no date is selected
// Convert dd-mm-yyyy to yyyy-mm-dd format
var dateParts = dateInput.split('-');
var formattedDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]); // Convert to a valid Date object
var currentTime = new Date(serverTime); // Create a Date object for the current server time
// Reset currentTime and formattedDate to midnight for date-only comparison
currentTime.setHours(0, 0, 0, 0);
formattedDate.setHours(0, 0, 0, 0);
// Get the current hour from the server time
var currentHour = serverTime.getHours();
var minHour = currentHour + 2; // Allow selection from 2 hours ahead
// Save original hour options only once
if (!hoursSelect.data('original-options')) {
hoursSelect.data('original-options', hoursSelect.find('option').clone());
}
// Restore the original hour options
hoursSelect.empty().append(hoursSelect.data('original-options').clone());
// Check if the selected date is today
var isToday = formattedDate.getTime() === currentTime.getTime();
// If today is selected, filter hours to only show those >= current time + 2 hours
if (isToday) {
hoursSelect.find('option').each(function () {
var hourValue = parseInt($(this).val(), 10);
if (isNaN(hourValue)) return; // Skip if it's not a valid hour value
// Remove options that are less than the minimum allowed hour
if (hourValue < minHour) {
$(this).remove();
}
});
}
// If no valid options remain, show a fallback message
if (hoursSelect.find('option').length === 0) {
hoursSelect.append('<option value="">No available hours</option>');
}
}
// Run the function when the date input changes
$('input[name="date-1"]').on('change', function () {
updateTimeOptions();
});
// Run the function immediately when the page loads in case the date is already selected
$(document).ready(function () {
updateTimeOptions();
});
This code successfully filters the time as expected; however, it prevents the form from being submitted.
I could not verify what exactly causing this.