jQuery DatePicker – Select a Date Programmatically

I have seen users asking how to programmatically select a date using jQuery UI DatePicker control.

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.”

Here’s an example. Assume you want to select a date “9-22-2010”

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Select a Date in jQuery DatePicker</title>
<
link rel="Stylesheet" type="text/css" href="
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
/>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</
script>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js">
</
script>

<
script type="text/javascript">
$(function () {
$("#devcurry-datepic").datepicker({
beforeShowDay: function (date) {
var selDate = "9-22-2010";
// month are 0 based, so +1.
var mm = date.getMonth() + 1, dd = date.getDate(),
yy = date.getFullYear();
// format date
var dt = mm + "-" + dd + "-" + yy;
if (dt == selDate) {
return [true, "ui-state-hover"];
}
return [true, ""];
}
});
});
</script>
</
head>
<
body>
<
input id="devcurry-datepic"/>
</
body>
</
html>

In the code shown above, we format the date and compare it with the date that has to be selected. If it matches, apply a css style ‘ui-state-hover’ to give it a selected feel. You can use any other class you want. The result is shown below with 22nd September selected.


image

Has anyone been able to use the setDate function in this scenario. It seems this function worked only in the previous versions of jQuery UI. Let me know if it has worked for you!



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

3 comments:

Crille said...

Do you know how to change the dateformat to year-month-day?

lo said...

HOw we could unselectable all days before current day?

prom said...

It is usefull article but what if I need to select more dates?