Thursday, January 07, 2010

Making 2 jQuery UI DatePickers Interact

Using the jQuery DatePicker is easy and provides a very functional calendar popup. What if you want to have two datepickers but you want the second one to respond to the selections in the first one? So every time you select a date in datepicker1, then datepicker2 immediately selects a date that is 7 days ahead.

Using the built in Date functions in JavaScript you can obtain the Date from the first picker when it is changed and set the date on the second picker after adding the required number of days.

<!DOCTYPE html>
    <html>
        <head>
            <link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
            <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
            <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
            <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.datepicker.js"></script>
            <script type="text/javascript">
           $(document).ready(function(){
              $("#datepicker1").datepicker();
              $("#datepicker2").datepicker();
              $("#datepicker1").change(function() {
              var date2 = $("#datepicker1").datepicker("getDate");
              date2.setDate(date2.getDate()+7);
              $("#datepicker2").datepicker("setDate", date2);
              });
                            });
             </script>
        </head>
         <body style="font-size:62.5%;">

              <div type="text" id="datepicker1"></div>
              <div type="text" id="datepicker2"></div>

          </body>
     </html>

No comments: