jQuery UI DatePicker – Programmatically selecting a Date

When the jQuery UI DatePicker shows up, the current date is selected by default as shown below:

jQuery UI DatePicker Default Date

Note: It was the 12th of February, 2010 when I tried this example.

However if you want to programmatically select a date, then here’s how to do so. We will select 15th of February, 2010:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title></title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</
script>
<
link rel="stylesheet" type="text/css" media="screen"
href="http://bit.ly/cNbe6T"/>

<
script type="text/javascript">
$(function() {
$("#datepic").datepicker();
// month is 0 based, hence for Feb we use 1
$('#datepic').datepicker('setDate', new Date(2010, 1, 15));
});
</script>
</
head>
<
body>
<
input id="datepic"/>
</
body>
</
html>

The output is now

jQuery UI DatePicker Select Date

You can also specify number of years, months or days from today. So for example, if I want to specify a date that is 1 month and 2 days from today, then here’s how you can do it

$('#datepic').datepicker('setDate', '+1m 2d');

OUTPUT

jQuery UI DatePicker Select Date






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

Yah, Cool. But it that possible to select multiple date like -

$('#datepicker').datepicker('setDate', new Date(2010, 1, 15));
$('#datepicker').datepicker('setDate', new Date(2010, 1, 17));

or

$('#datepicker').datepicker('setDate', array);