Add a Date Picker to Your Forms

The other day, I found myself in need of a nice, simple date picker for a form I’m developing. Being a fan of the MooTools javascript framework, I headed off to Google to look for a date picker that utilizes MooTools. I found a real winner.

The MooTools DatePicker from MonkeyPhysics is extremely simple to implement, works beautifully and is extremely customizable. On the site, you can also download four different “skins” for the date picker. For my purposes, I went ahead and stuck with the default skin (which only requires the download of a CSS file), but I can certainly see the value in some of the other themes. The page includes a lot of nice examples and some great documentation. In addition to what’s provided on that site, I’ve added a handful of tips after the jump.

Some Tips

To get the date picker not to allow people to pick dates that have already passed, you can use the following script. The script below will generate a string that holds the current date and use it as the minimum date shown in the date picker. In this example, I’ve used the CSS class of “datefield” as the class of form element that automatically gets a date picker added.

var myDate = new Date();
var myYear = myDate.getFullYear();
var myMonth = (myDate.getMonth()+1); // Javascript months range from 0-11 rather than 1-12
var myDay = myDate.getDate();
new DatePicker('.datefield',minDate { date: myMonth+'-'+myDay+'-'+myYear, format: 'm-d-Y' });

In Internet Explorer 6, the date picker (along with any other absolutely positioned item) will show up behind any select elements in your form. In order to avoid this problem, you can temporarily hide all of the select elements on the page when you open the calendar.

new DatePicker('.datefield',onShow: function() {
if (Browser.Engine.trident4) $$('select').setStyle('visibility', 'hidden');
},onClose: function() {
if (Browser.Engine.trident4) $$('select').setStyle('visibility', '');

To add a date picker to a single element, you will need to assign an HTML ID to the element. For the example below, I will be using “myDate” as the HTML ID.

new DatePicker('#myDate');

The second example (the IE6 tip) was taken from one of the comments on the original DatePicker post. I came up with the other two examples. The first has been tested, but the third has not. It should work, though.

I hope this helps the next time you’re looking for a user-friendly way to allow users to add dates to your forms.