jQuery date chooser

by Blake Schwendiman on May 12, 2009

Providing a simple, consistent method for allowing your end-users to enter a date in a form is another great reason to use jQuery and jQuery UI. There have been many date selection tools created — you may have invented one yourself — but few are as great as the jQuery UI datepicker.

As with all things jQuery, there is very little required. Just set up a form, add a quick call to jQuery and you’re done. By default, when the datepicker is bound to an edit input, all that is required is to click on the edit (or tab into it) and the calendar control will appear.

[-]?View Code JAVASCRIPT
<form>
  <fieldset>
    <label>Select a date: <input type="text" id="the_date" name="the_date" /></label>
  </fieldset>
</form>
 
<script type="text/javascript">
  jQuery('#the_date').datepicker();
</script>

Here it is in action (click on the input field):

Personally, I like a little more visual indication on date fields. Providing a calendar icon to the right of the input field has become a de facto standard on the web, so I’ll show how simple it is to add that to a jQuery UI datepicker.

[-]?View Code JAVASCRIPT
<form>
  <fieldset>
    <label>Select a date: <input type="text" id="the_date" name="the_date" /></label>
  </fieldset>
</form>
 
<script type="text/javascript">
  jQuery('#the_date').datepicker({showOn: 'both', buttonImage: '/wp-content/themes/thesis/custom/images/ical.png', buttonImageOnly: true});
</script>

As you can see, I added a small set of options to the datepicker() method. The showOn option indicates to show the calendar when the button is clicked and when the control has focus. The buttonImage option is the URL to the image and the buttonImageOnly option indicates to display the image alone, not as part of an actual button control. Visit the jQuery UI site for more datepicker control options.

Here it is with the calendar button (download the button image here):

The jQuery UI datepicker provides a great deal of flexibility and control with a minimum required effort. Check it out for yourself!

Comments:

Comments on this entry are closed.