jQuery UI is Awesome: Datepicker Functionality Explained Easily

I have used jQuery UI for quite some time now, including the wonderful Datepicker. However, I just recently starting using a lot of the options and methods available, and thought I would show an example of how extendable it really is. Check out this jQuery:

	$(function() {
		$( "#my_date" ).datepicker({ 
		dateFormat: "mm/dd/yy",
		defaultDate: "01/01/1970",
 		minDate: "01/01/1925",
		maxDate: "12/31/2011",
		changeMonth: true,
		changeYear: true,
		yearRange: "1925:2011",
		onClose: function(dateText, inst) {
			var validDate = $.datepicker.formatDate( "mm/dd/yy", $('#my_date').datepicker('getDate'));
				$('#my_date').datepicker('setDate', validDate);
			}
		});
	});

Then, place the text input element into the HTML:

<input name="my_date" id="my_date" type="text" value="01/01/1970" />

Let’s talk about what this actually does.

  • $( “#my_date” ).datepicker({ invokes Datepicker on the element with id “my_date”, the text input area.
  • dateFormat: “mm/dd/yy”, tells Datepicker to use the date format consistent with 07/28/1974. Yes, “yy” means four-digit year, and “y” means two-digit year. I wasted a lot of time figuring that one out!
  • defaultDate: “01/01/1970”, tells Datepicker to open with January 1st, 1970 as the default selection.
  • minDate: “01/01/1925”, and maxDate: “12/31/2011”, create the selectable valid date range. Users would not be able to select any date before 1925, or after 2011 in this case.
  • changeMonth: true, includes a drop down menu for users to easily change the month without having to click and click and click.
  • changeYear: true, includes a drop down menu for users to easily change the year without having to click and click and click.
  • yearRange: “1925:2011”, sets the range of years available in the downdown menu for changing the year.
  • onClose: function(dateText, inst) { … } checks the date entered after Datepicker closes. This ensures that if a user manually types a date in using the keyboard, and it isn’t valid, it will restore the default date. Also, if the user puts in a date which can be interpreted, such as “3/1/89”, it will reformat the typing in the input box to be populated with “03/01/1989”.

    I hope this example helps, as I pieced a lot of this together from different Google finds.

  • 3 thoughts on “jQuery UI is Awesome: Datepicker Functionality Explained Easily

    1. I’m glad to help – this is clearly very basic stuff, not rocket science, but I didn’t see a clear example explaining all the options clearly in the documentation. I also wish they’d stuck with “yyyy” for four digit year – that is absurdly bass-ackwards.

    Leave a Reply