jQuery UI date picker - how to set the start date of your second calendar

set the mindate of a second calendar using jquery ui

If you haven't already looked into using the jquery UI calendars, you really should! One of my latest projects, www.hertzflydrive.com, uses these calendars on the homepage. They are quick to setup and offer loads of options that make them very flexible for anyone looking to use date pickers on their forms.

One of the most common setups is to use two calendars to let users pick 'From - To' dates. Placing two textboxes and setting them up to use the calendars is easy (and for this post I am assuming you can at least do that much) but what if we only want our second calendar to only allow the user to select dates on or after the date entered in the first calendar?

Well the good news is that this is easy to do using a custom function that is called before the calendar is displayed to the end user. The script below shows the jQuery for setting up two calendars on your form and the custom function to ensure that the dates the end user selects on the second calendar are either after today's date or after the value entered in our 'From' calendar.

jQuery - save as calendar-config.js in a folder called scripts:

$().ready(function() {
    $('.pUpDate, .dOffDate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        beforeShow: customRange,
        dateFormat: 'dd-mm-yy',
        showOn: 'both',
        buttonImage: 'images/calendar-icon.gif',
        buttonImageOnly: true,
        buttonText: 'Show Date Picker'
    });
});
function customRange(a) {
    var b = new Date();
    var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
    if (a.id == 'DropoffDate') {
        if ($('.pUpDate').datepicker('getDate') != null) {
            c = $('.pUpDate').datepicker('getDate');
        }
    }
    return {
        minDate: c
    }
}

The custom range function above should be self explanatory. We pass in the id of the element we clicked on (i.e. which textbox we're currently in) and if that textbox is the drop-off textbox we want to set the min date to be the value entered in the Pick-up textbox, assuming it has a value.

HTML:

date picker dual calendar example





   

To help you get started you can download a working example of this demo here - min date jquery demo.zip (67.37 kb). To view it in action head over to hertzflydrive.com.

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets