Friday, May 6, 2011

jQuery - Datepicker - Disable Specific Dates

You can disable specific dates with the jQuery Datepicker using the beforeShowDay event.

var unavailableDates = ["9-5-2011","14-5-2011","15-5-2011"];

function unavailable(date) {
  dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
  if ($.inArray(dmy, unavailableDates) < 0) {
    return [true
,"","Book Now"];
  } else {
    return [false
,"","Booked Out"];
  }
}

$('#iDate').datepicker({ beforeShowDay: unavailable });

Note: iDate in the last line is the name of the HTML form input element.

To see a working example with some more features please see the jsFiddle example: HERE
Anonymous said...

Cool - that worked for me... Thanks!

Anonymous said...

its awsummmmmmmm wonderful thank you so much you solved my problem.

Anonymous said...

thank you :)

Anonymous said...

I works perfectly, thanks. Would you know how to load the dates of the array dynamically, from a database?

Tokes said...

First you would need to make an SJAX call to a PHP file that would have something like this:

$dates = array();
$sqldata = mysql_query("SELECT `date` FROM `date_table`);
while($date = mysql_fetch_assoc($sqldata)) {
$dates[] = $date;
}
echo json_encode($dates);

Then on the JavaScript side:

unavailableDates = new Array();
unavailableDates = eval("("+result+")");

result being the returned data from the SJAX call see:
http://tokenposts.blogspot.com/2011/05/javascript-ajax-sjax-submit-form-data.html

Anonymous said...

Nice one.. Was wondering how to and did not noticed this option in the documentation.. So thanks :)

Anonymous said...

thanks very useful

Mukesh B. Rane said...

hey thank you very much it's really nice

Jenny said...

Would you be able to show a jsfiddle so that all dates are disabled except for ones in the array?

Tokes said...

Hi Jenny,

Simply swap the IF ELSE statement.

http://jsfiddle.net/XxwSZ/

EMG said...

It is possible to get a working example for the people that doesn't know to integrate it in a webpage??? (the people...is me...) Tks....

Anonymous said...

just what I was looking for, thanks!

Anonymous said...

Its working.
But not working with dates
var unavailableDates = ["09-05-2011","14-05-2011","15-05-2011"];

Jim said...

Great post! :D

I have looked for something like this for a looong time! :D

Greg said...

Hi, thanks a lot for that, it's working perfect except one thing, when I use ajax to get the unavailability from the database, i get a javascript error:

ba is undefined
/js/libs/jquery-ui-1.8.18.custom.min.js
Line 47

if I remove the ajax statement and use the basic function I dont get the error. I compared the array return from the db to the one in the example and they look exactly the same. here is my js function:
$.post(
base_url+"booking/getDates", {house: house, room: room},
function(data){
unavailableDates = new Array();
unavailableDates = data;
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
console.log("unavailableDates: ", unavailableDates);
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false,"","Unavailable"];
}
},"json"
);

Thank you in advance

Jorge Navas Alejo said...

Hello!

Amazing job dude. Just one question:

Is it possible to combine it with more clauses? In my cause, I'd like to disable specific dates AND weekends.

Thanks a lot!

Tokes said...

@Jorge
Please see more advanced example here http://jsfiddle.net/6SyfY/
I have allowed disabling any days you want, the example shows weekends.

Anonymous said...

Fantastic example. I was wondering how you would disable specific dates after the datepicker was initially configured with beforeshowdates?

Craig Constable said...

You can remove the date picker using:
$('#iDate').datepicker("destroy");

You can then update the unavailableDates array and re-add the datepicker using:
$('#iDate').datepicker({ beforeShowDay: unavailable });

Anonymous said...

Thanks Craig. After two days of searching around I'm thinking you're right about that. Was hoping that there was a way to update the element without destroying it.

Craig Constable said...

If you are simply changing the unavailableDates array you could just call: $('#iDate').datepicker("refresh");

Anonymous said...

It doesn't work.

Craig Constable said...

What issue are you having? You can see a working example in the jsFiddle link.

Anonymous said...

It's very usefull, thanx...

Anonymous said...

thnax for posting ...it solved mine problem too

Anonymous said...

but can tell me how to overwrite a class of "td" element ?

Anonymous said...

Hola, soy novato en esto y necesito las bondades de esta herramienta. Me podrían decir cómo inserto el código en mi sitio. Tengo instalado el datepicker 1.7.2.min.js y 1.8.22.custom.min.js, con el tema le-frog; al cual lo pasé al español y con el formato dd.mm.aa. La pregunta sería dónde tendría que insertar el código js y si le tengo que hacer alguna modificación respecto mi instalación y dónde tendría que insertar las nuevas líneas css. He intentado por horas varias cosas y no logro que funcione. Espero vuestra ayuda y gracias!!!!!!

Craig Constable said...

Hola,

Probablemente la mejor manera de insertar este código en la parte inferior de su página en una etiqueta SCRIPT. cambiar a dd.mm.yy es fácil basta con cambiar la línea:
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
a
dmy = date.getDate() + "." + (date.getMonth()+1) + "." + date.getFullYear();

si usted necesita un 0 a la izquierda se puede ver el ejemplo que hice aquí: http://jsfiddle.net/6SyfY/ se añade un 0 a la salida y lleva a los dos últimos dígitos.

Si quiere añadir css se puede ir ya sea en un archivo externo o en la propia página.

Espero que esto ayude!

Anonymous said...

Thank you for this helpful code.

cheers

Anonymous said...

Great option, helped a lot

Anonymous said...

Hi.
It's stop working when date format is [d-m-Y];
and only work for [j-n-Y];
see this link http://hostharbour.com/php_date.php
help me for [d-m-y] format.

Thanks

Anonymous said...

it's work well for "9-5-2011" but not work for "09-05-2011".
help me guys..

Craig Constable said...

Checkout the jsFiddle I linked in the post http://jsfiddle.net/6SyfY/

Anonymous said...

Perfect answer.
:) :)

-Frank

Tapwell Bathrooms said...

Perfect and simple for our needs.

Is there any way to use 'minDate: +x' but only include days that are available? e.g. If I set only weekdays to available, and I set minDate to 2, and the user views the calendar on a Friday, Monday will be unavailable.

Craig Constable said...

Hi Tapwell Bathrooms,

Can probably be simplified but here is a working sample: http://jsfiddle.net/6d48d/

Dan / Tapwell said...

Amazing, much appreciated!

stevo said...

For days whose date is less than ten you need the following instead:

function unavailable_b(date) {
var dmy = ("0" + date.getDate()).slice(-2) + "-" + ("0" + (date.getMonth()+1)).slice(-2) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) < 0) {
return [true,"","Book Now"];
} else {
return [false,"","Booked Out"];
}
}

Craig Constable said...

Hi Stevo,

Yes that is in the advanced example in the notes.
And no it is only needed when using dates with a preceding zero.

Heather Kelly said...

Possible to block out the two weeks from the date of purchase? So if the order date is today, can the next two weeks be grated out?

Craig Constable said...

Hi Heather,
Yes. If you have the order date recorded in a database you can simply retrieve that and use it in a javascript function that creates an array of dates starting with that date until the array has a count of 14 dates.
PHP:
$result = mysql_query("SELECT max(`order_date`) FROM `orders`");
$order_date = mysql_result($result, 0);
echo "[script]order_date = '" . $order_date . "';[/script]

JavaScript:
order_date = new Date(order_date);
unavailableDates = new Array();
while (unavailableDates.length < 14) {
tempdate = new Date();
tempdate.setDate(order_date.getDate()+unavailableDates.length);
unavailableDates.push([tempdate.getDate(),tempdate.getMonth()+1,tempdate.getFullYear].join('-'));
}
Note: Not tested but should work or at least give you the idea of how to accomplish this task. Also script tags were changed from <> to []

Heather Kelly said...

Thanks for your help Craig - a big beyond my capabilities I think...i need to hire a programmer!!

Heather Kelly said...

Can anyone help with the coding for greying out 12 weeks from the date of the order? I've re-read this forum but still haven't been able to figure it out. so if someone orders today, I want to grey out the dates between today and 12 weeks from then. Thanks a mil.

Heather Kelly said...

At the very least I need to make the field required. Thanks!

Craig Constable said...

Hi Heather, http://jsfiddle.net/Craigus/6SyfY/846/

Baby Giz said...

Wow!! Thank you!

Rukeshreddy PT said...

How to download javascript files from this jsfiddle...Please help me

Liz OXYwater said...

How do you turn off the following 7 days after today's date? from the delivery date picker?

Anonymous said...

Hi! In New Zealand we always put the date first, then the month, then year....
At the moment it's showing month -date- year... How can I change that?

Craig Constable said...

This is also using day-month-year so I'm not sure what you mean.

Post a Comment