Customize specific disabled dates in a range using jQuery UI datepicker
I am using jQuery UI datepicker for a form where users request a school visit. There is a date range in which tours are held, and within this range, the site administrator can disable certain days that are booked. No problem yet:
/* array of booked dates generated from CMS backend */
var disabledDates = [
'2015-05-06',
'2015-05-08' // examples
];
$('[name="date_of_visit"]').datepicker({
minDate: '4/30/2015', // Range start
maxDate: '10/1/2015', // Range end
beforeShowDay: function(date) { // Disable custom dates
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [$.inArray(string, disabledDates) == -1];
}
});
I got the code beforeShowDay
from this post: JQuery UI datepicker. Disable array of dates
I know I can add a class to disabled items with a second parameter, but it adds it on all disabled dates, including those outside minDate
and maxDate
:
beforeShowDay : a function that takes a date as a parameter and should return an array with:
0: true / false indicating whether this date can be selected
1: CSS class name to add to date cell or "" for the default presentation
2: optional tooltip for this dateThe function is called for every day in the datepicker before it is displayed.
However, the client has requested that only "booked" dates have a visual indication that the date is not available (other than the default disabled state). There won't be that many, maybe 4 or 5. It makes sense to me.
Is there a way to adjust only the dates disabled by a feature beforeShowDay
in my setup, or some other solution to achieve what I need? jsFiddle demo
source to share
Wesley, I looked at your requirement and looked at the requirement you needed and I think as it might be required by me as well as it was unique in itself so I researched the code and did what you wanted. I am pasting the code below with a little explanation of the same: -
Below is the JQuery code:
var disabledDates = [
'2015-05-06',
'2015-05-08'
];
$('input').datepicker({
minDate: '4/30/2015',
maxDate: '10/1/2015',
beforeShowDay: function(date){
var str = jQuery.datepicker.formatDate('yy-mm-dd', date);
var minDateArr = $(this).datepicker( "option", "minDate" ).split('/')
var minDate = new Date(minDateArr[2],minDateArr[0]-1,minDateArr[1]); //Don't remove the -1 from minDateArr[0]-1 as the Javascript dates starts with 0.
if ($.inArray(str, disabledDates) != -1){
return [false, 'special']
}
else if(date < minDate ){
return [false, 'not-special']
}
else{
return [true,"special"];
}
}
});
A bit of manipulation in CSS: -
.special span {
color: red !important; /* should only apply to may 6 and 8 */
}
.not-special span {
color: green !important;
}
And most importantly, there must be an input tag: -
<input>
Also below is Js Fiddle link for the same: - http://jsfiddle.net/ckk6hzzu/
Hopefully this is what you needed and expecting it helps others where it can be used to book / book sites.
source to share