Highlight Specific Dates in jQuery UI DatePicker

Yesterday for one of my requirement, I need to show all the public holiday dates as highlighted in jQuery UI Datepicker so the user will come to know that this is a holiday. So I have implemented the solution and sharing with you. This might be useful for you when you want highlight specific date. In this post, I will show you how to highlight dates in jQuery UI DatePicker control.

To highlight a date(s), it is important to apply some kind of style so that it looks different from others dates. So define a CSS class, which will be used to show highlighted dates.

//Code Starts
.Highlighted a{
   background-color : Green !important;
   background-image :none !important;
   color: White !important;
   font-weight:bold !important;
   font-size: 12pt;
}
?//Code Ends

First, create an array of dates which should be highlighted. In the below jQuery code, you will see the array index value is also a date object and the value is also a date object.

//Code Starts
var SelectedDates = {};
SelectedDates[new Date('04/05/2012')] = new Date('04/05/2012');
SelectedDates[new Date('05/04/2012')] = new Date('05/04/2012');
SelectedDates[new Date('06/06/2012')] = new Date('06/06/2012');
//Code Ends

Now, the DatePicker control provide "beforeShowDay" event, which gets called before building the control. So use this event to highlight the date.

//Code Starts
$('#txtDate').datepicker({
   beforeShowDay: function(date) 
   {
      var Highlight = SelectedDates[date];
      if (Highlight) {
         return [true, "Highlighted", Highlight];
      }
      else {
         return [true, '', ''];
      }
   }
});
//Code Ends

So the complete code is,

//Code Starts
$(document).ready(function() {
    var SelectedDates = {};
    SelectedDates[new Date('04/05/2012')] = new Date('04/05/2012');
    SelectedDates[new Date('05/04/2012')] = new Date('05/04/2012');
    SelectedDates[new Date('06/06/2012')] = new Date('06/06/2012');

    $('#txtDate').datepicker({
        beforeShowDay: function(date) {
            var Highlight = SelectedDates[date];
            if (Highlight) {
                return [true, "Highlighted", Highlight];
            }
            else {
                return [true, '', ''];
            }
        }
    });
});?
//Code Ends

See result below.

See Complete Code

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...