jquery

Enable Custom Days in jQuery Datepicker

jQuery Datepicker is an awesome way to present a calendar to your users and let them choose a day.  But sometimes your clients are just total pains.  You know who you are. So your client doesn’t do business on Thursdays?  Or what if they just aren’t available on May 6th, 2027?  Do you know how to enable a certain set of days or even specific days of the week?  Now you can.

To get started, be sure you’ve included the jquery UI framework (we’re using 1.9.2 below) and create a text input that will later become your datepicker.

<input type='text' id='txtDate' />

To get the standard calendar using jquery Datepicker, you would initialize it like so

<script>
    $('#txtDate').datepicker();
</script>

Now we’re going to utilize a little known function of the datePicker called beforeShowDay.


beforeShowDay Function(Date). Default: $.noop

A function that takes a date as a parameter and returns one of the following values:

  • undefined to have no effect
  • A Boolean, indicating whether or not this date is selectable
  • A String representing additional CSS classes to apply to the date’s cell
  • An object with the following properties:
    • enabled: same as the Boolean value above
    • classes: same as the String value above
    • tooltip: a tooltip to apply to this date, via the title HTML attribute

An example of usage is as follows. The below example only allows weekends and the two dates in the custom array to be selected.



The function works by returning true or false to indicate whether the day in question will be enabled or not.

return [dt.getDay() == 0 || dt.getDay() == 6 || available(dt), "" ];

The first two tests check if the day passed in (dt) is a Saturday or Sunday, and the final test decides if the passed in day is in the predefined list of valid days defined in the variable “availableDates”.

This helped me get out of a particularly “picky” situation, hopefully it will do the same for at least one of you.

Erik Runia

Erik Runia

While still a young lad, Erik discovered that learning to program gave him infinite lives while playing Gorillas on a Windows 3.1 machine...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>