Highlight dates in jquery UI datepicker
Dates in JS are instances of object Date
, so you can't check properly if dates are equal using ==
or ===
.
Simple solution:
var your_dates = [
new Date(2017, 4, 25),
new Date(2017, 4, 23)
];
$( "#some_selector" ).datepicker({
beforeShowDay: function(date) {
are_dates_equal = d => d.getTime() === date.getTime();
if(your_dates.some(are_dates_equal)) {
return [true, 'ui-state-active', ''];
}
return [true, '', ''];
}
})
Have a look at the documentation.
beforeShowDay The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, [1] equal to a CSS class name(s) or '' for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.
This means that you need to create a function that will take a date and return an array of parameters where values are:
- boolean - indicates if date can be selected
- string - name of the css class that will be aplied to the date
- string - an optional popup tooltip for this date
here is an example:
var your_dates = [new Date(2011, 7, 7),new Date(2011, 7, 8)]; // just some dates.
$('#whatever').datepicker({
beforeShowDay: function(date) {
// check if date is in your array of dates
if($.inArray(date, your_dates)) {
// if it is return the following.
return [true, 'css-class-to-highlight', 'tooltip text'];
} else {
// default
return [true, '', ''];
}
}
});
and now you can add the style to highlight the date
<style>
.css-class-to-highlight{
background-color: #ff0;
}
</style>
I solved the issue using
var disabledDays = ["2011-7-21","2011-7-24","2011-7-27","2011-7-28"];
var date = new Date();
jQuery(document).ready(function() {
$( "#dateselector").datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: function(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray(y + '-' + (m+1) + '-' + d,disabledDays) != -1) {
//return [false];
return [true, 'ui-state-active', ''];
}
}
return [true];
}
});
});
Found the most voted answer not working. Updated the code little bit to make it working. $.inArray() mostly search for indexOf(). Also we can't compare two dates directly for equality. Reference : Compare two dates with JavaScript
function inArrayDates(needle, haystack){
var found = 0;
for (var i=0, len=haystack.length;i<len;i++) {
if (haystack[i].getTime() == needle.getTime()) return i;
found++;
}
return -1;
}
And update the accepted function as
if(inArrayDates(date, markDates) != -1) {
return [true, 'selected-highlight', 'tooltip here'];
} else {
return [true, '', ''];
}