如何修改jQuery Datepicker的beforeShowDay,允许选择周日至周四?
Sure thing! You can absolutely customize the beforeShowDay callback to allow only Sunday through Thursday instead of the default Monday-Friday that $.datepicker.noWeekends enforces. Here's a straightforward solution:
The core idea is to replace $.datepicker.noWeekends with a custom function that checks the day of the week. Remember: JavaScript's Date.getDay() returns 0 for Sunday, 1 for Monday, up to 6 for Saturday. We want to enable days where the value is 0 (Sun) to 4 (Thu), and disable Friday (5) and Saturday (6).
Here's your modified code with the custom validation integrated:
$(function () { // Custom function to allow Sunday through Thursday const allowSunToThu = function(date) { const dayOfWeek = date.getDay(); // Return [true, ...] if day is 0-4 (Sun-Thu), else [false, ...] return [(dayOfWeek >= 0 && dayOfWeek <= 4), '']; }; $("#datepicker").datepicker({ onSelect: function () { $("#sched_macs_button").show(300); }, dateFormat: 'yy-mm-dd', changeMonth: true, beforeShowDay: allowSunToThu, // Use our custom validation here numberOfMonths: 1, minDate: dateToday }); });
A quick breakdown of how this works:
- The
allowSunToThufunction takes a date object as input. - We grab the day of the week using
date.getDay(). - We return an array where:
- The first element is
trueif the day is allowed (making it selectable), orfalseif it should be disabled (greyed out and unclickable). - The second element is an optional CSS class (we left it empty here, but you could add a class name if you want to style allowed/disabled dates differently).
- The first element is
This approach is clean, uses Datepicker's built-in callback system as intended, and is easy to adjust if you ever need to change the allowed days later.
内容的提问来源于stack exchange,提问作者spas2k

