Friday, November 28, 2008

Whether you’re an airline, task manager, or just have a birthdate field on your registration form, a popup date picker makes selecting dates considerably easier for users, and overall enhances the functionality and feel of the site. jQuery UI provides a datepicker widget that can easily be incorporated into your site.

The Finished Datepicker Example

Getting Started

In order to use the datepicker, we need to download it from the jQuery UI download page and link it into our page as we do with the jQuery library. Applying the datepicker requires no HTML changes, and instead simply attaches itself to existing input fields. This is done with a single line of code:

$('#trip input#leavedate').datepicker();

The standard date picker that is shown is admittedly fairly ugly and impractical in both size and look.

Customization

The real power of jQuery’s datepicker is the level of customization. We’ll go through three quick steps toward creating a datepicker that’s right for our example situation. This should give you enough examples and variations for you to choose the right parameters for your situation, too.

Styling

First up, we’re going to make the calendar popup itself a little more appealing for the sake of making more practical decisions around the actual placement of the calendar. jQuery provides a handful of CSS stylesheets to chose from, but you can of course always write your own or modify them if you don’t like them. With the first theme, the calendar looks like this:

Date Format

Specifying the date format is just a matter of passing a parameter to the .datepicker() initialization function. Here are some common formats:

This leaves you with control over the order, separaters (slash, dash, or space), whether or not you want leading zeros on your days or months, whether you want numbers or words, and what you include or omit (year, day name, etc.).

These affect the format that the date shows up in the field after you select it:

Behavior

The last customization that we’re going to look at here is the popup behavior. By default, the event is attached to the focus of the input field that the datepicker widget is attached to. This can easily be changed so that the event is attached to either a button or an image next to the field instead.

Wrapping Everything Up

These customizations are what make the jQuery datepicker UI widget so powerful, as the widget is practical in a variety of situations. The following is the completed example using the customizations discussed above.