Home > Javascript > Chaining 2 jQuery UI Datepickers

Chaining 2 jQuery UI Datepickers

A simple example to chain 2 jQuery UI datepickers such that when a date is selected in the first datepicker (a.k.a. the ‘from date‘, date1), the minimum date in the second datepicker (a.k.a. the ‘to date‘, date2) is set accordingly. Similarly it handles the case where the ‘to date‘ is selected before the ‘from date‘, in which case the maximum date in the ‘from date‘ is lesser than the ‘to date‘ but before current date.

Relevant HTML For Datepicker Placeholders

<p><input type="text" name="date1" id="date1" /></p>
<p><input type="text" name="date2" id="date2" /></p>

Relevant jQuery Setup Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script>
  $(document).ready(function() {  
    $('#date1').datepicker({
      autoSize: true, 
      constrainInput: true, 
      dateFormat: 'ddMyy', 
      minDate: 0, 
      maxDate: '+90D', 
      onSelect: function(dateText, inst) { 
        $('#date2').datepicker("option", "minDate",dateText); 
      } 
    });
    $('#date2').datepicker({
      autoSize: true, 
      constrainInput: true, 
      dateFormat: 'ddMyy', 
      minDate: 0, 
      maxDate: '+90D', 
      onSelect: function(dateText, inst) { 
        $('#date1').datepicker("option", "maxDate",dateText); 
      } 
    });
    //Other setup
  });
</script>

In the jQuery setup code above, I have also set the following

  • Do not allow selection of dates before current date (minDate: 0)
  • Do not allow selection of dates 90 days after current date (maxDate: '+90D')
  • Date format similar to ‘17Jun2010
  • The ‘constrainInput: true‘ indicates that the input field is constrained to those characters allowed by the current dateFormat.
Categories: Javascript Tags:
  1. ChrisO
    June 20th, 2010 at 21:42 | #1

    Thanks for the post. Very helpful. What is the syntax for making the minDate of the second date textbox to be 1 DAY AFTER the FROM date? Basically, i need to add 1 to the DATE1 date to be the minDate for DATE2.

    Thanks.

  2. merkillinenn
    September 1st, 2010 at 15:40 | #2

    Thank you, this really saved me alot of work hours!

  3. September 12th, 2010 at 00:29 | #3

    Hi – I keep getting type errors thrown by the event call. WHat script versions are you using? Thanks.

  4. sbsh
    July 8th, 2011 at 19:24 | #4

    Hi nirmalya
    Thank you

  1. No trackbacks yet.