Monday, March 4, 2013

jQuery datepicker range : Select date with From and To.

    jQuery datepicker is one the sophisticated ui components jQuery provides. There are loads of options to customize the datepicker as per your needs. Generally it's used on a text field, which when clicked opens an interactive calendar. User selects a date and input field gets filled with the date in appropriate date format as per our configuration. 

  There are many uses of this kind of datepicker. One of them is to select a range of dates with structure like select date From and select date To. Just the way shown below :


Datepicker range
   
     Creating this kind of range datepickers in jQuery is very easy. You need to use onSelect callback function along with minDate and maxDate. The idea is that when user selects "from" date, the selected date is set as minDate for "to" datepicker. And when user selects "to" date, the selected date is set as maxDate for "from" datepicker. This enables user to select a date in appropriate range only and you need not to perform any range validation like say "to" is not older than "from". 

    Consider "from" and "to" are ids of from and to datepicker's text fields. I believe you have included js files for jQuery and jQuery UI along with css file of UI. The code snippet looks like this : 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 $( "#from" ).datepicker({
      changeMonth: true,  
      changeYear:true,      
      maxDate:0,
      onSelect: function( selectedDate ) {
        $( "#to" ).datepicker( "option", "minDate", selectedDate );
      }
    });
    $( "#to" ).datepicker({      
      changeMonth: true,   
      changeYear:true,
      maxDate:0,
      onSelect: function( selectedDate ) {
        $( "#from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });


    Please take note of how onSelect function is used and how minDate and maxDate are set. 
    Setting maxDate to 0 (today) is used to prevent user from selecting date larger than today's date, this is used mainly because range datepickers are generally used to select date from past like selecting range for showing history logs, college years etc. You can use or remove that as per your needs.

   This fiddle shows how it works :