基于日期与当前时间动态调整时间下拉选框的JS实现咨询
Absolutely! You can fully implement this required logic using jQuery's on('change') event (or vanilla JavaScript if you prefer). Let's walk through a complete solution tailored to your form, including all the special case handling you outlined.
Quick Pre-requisite Fix
First, I noticed your form has duplicate data_cmd (date picker) and ora_ridicare (time select) elements. Make sure to remove the duplicate set so your JavaScript can target the correct fields without conflicts.
Complete JavaScript Implementation
Here's the code you can add to your page (make sure it loads after jQuery, and wraps in a $(document).ready() block to ensure elements exist when the code runs):
$(document).ready(function() { // Helper function to generate time options based on allowed range function generateTimeOptions(startHour, endHour, minTime = null) { let options = '<option value="">Selectează ora</option>'; // Default empty option for (let hour = startHour; hour <= endHour; hour++) { const timeStr = `${hour.toString().padStart(2, '0')}:00`; // Skip times earlier than minTime if provided if (minTime && new Date(`2000-01-01T${timeStr}`) < minTime) { continue; } options += `<option value="${timeStr}">${timeStr}</option>`; } return options; } // Handle date picker change event $('#data_cmd').on('change', function() { const selectedDateStr = $(this).val(); const selectedDate = new Date(selectedDateStr); const today = new Date(); today.setHours(0, 0, 0, 0); // Normalize today to midnight for date comparison const selectedDay = selectedDate.getDay(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday let startHour, endHour; let minTime = null; // Check if selected date is today const isToday = selectedDate.getTime() === today.getTime(); // Set base time range based on day of week switch(selectedDay) { case 0: // Sunday $('#ora_ridicare').html('<option value="">Niciun orar disponibil</option>'); return; case 6: // Saturday startHour = 9; endHour = 14; break; default: // Monday-Friday startHour = 9; endHour = 17; break; } // Handle special cases for today if (isToday) { const currentTime = new Date(); const currentHour = currentTime.getHours(); const currentMinute = currentTime.getMinutes(); // Case 1: Monday today, current time is 11:17 AM (or later before 12:00) if (selectedDay === 1 && currentHour === 11 && currentMinute >= 17) { minTime = new Date('2000-01-01T12:00'); } // Case 2: Saturday today, current time is 13:00 or later else if (selectedDay === 6 && currentHour >= 13) { // Only 14:00 is available $('#ora_ridicare').html('<option value="14:00">14:00</option>'); return; } // General case: filter out times earlier than current time else { minTime = new Date(`2000-01-01T${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`); } } // Generate and update time options const timeOptions = generateTimeOptions(startHour, endHour, minTime); $('#ora_ridicare').html(timeOptions); }); // Initialize time options on page load (if date is pre-filled) if ($('#data_cmd').val()) { $('#data_cmd').trigger('change'); } });
Key Logic Breakdown
Let's go through how this handles all your requirements:
Day-of-Week Time Ranges:
- Monday-Friday: Generates options from
09:00to17:00 - Saturday: Generates options from
09:00to14:00 - Sunday: Replaces the select with a message that no times are available
- Monday-Friday: Generates options from
Same-Day Special Cases:
- Monday, current time ≥ 11:17: Filters out all times before
12:00, leaving only12:00to17:00 - Saturday, current time ≥ 13:00: Directly sets the only available option to
14:00 - General same-day scenario: Automatically filters out any times that are earlier than the current system time
- Monday, current time ≥ 11:17: Filters out all times before
Future Date Handling:
- For any selected date that's not today (like your example of selecting
1/12/2020when today is29/11/2020), it uses the base time range for that day of the week (since there's no need to compare current time to a future date)
- For any selected date that's not today (like your example of selecting
Notes for Your Form
- Make sure your date input's
data-date-formatmatches the browser's native date picker output (which isYYYY-MM-DD, so your current setup is correct) - The reset button uses
document.location.reload()— this will re-initialize the form, which works fine with our code since we trigger thechangeevent on page load if the date is pre-filled
内容的提问来源于stack exchange,提问作者Cristian-Angelo Lungu

