Choose which Dates are Selectable in the jQuery DatePicker

While using the DatePicker control for a client, they had a requirement where users should be able to select only weekends (Saturday, Sunday) from the DatePicker.

The DatePicker beforeShowDay event is ideal for this type of a requirement. As described in the documentation “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 is how we will use this event to prevent users from selecting certain days in the jQuery UI DatePicker

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#datepick").datepicker({ beforeShowDay:
function(dt) {
return [dt.getDay() == 0 dt.getDay() == 6, ""];

where 'datepick' is the DatePicker control defined like this:

<input id="datepick" type="text" />

On running the code, you will see that only dates that fall on weekends can be selected

jQuery UI DatePicker

See a Live Demo

Note: The same example can be run for a DatePicker in an ASP.NET Page. Just replace the HTML TextBox with an ASP.NET TextBox control

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Anonymous said...

thanks for lesson and how do I do a date format like 'DD, d MM, yy' so i have the day name shows up? Thanks