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

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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