如何根据第一个日期选择器更改第二个日期选择器的日期?

How to change 2nd Date picker date base on 1st Date picker?

我有两个日期选择器用于开始日期和结束日期。当页面加载结束日期距当前日期还有 3 个月且开始日期为当前日期时自动执行。

所以,如果我在我的日期选择器中更改开始日期,我的第二个日期选择器需要自动更新。

怎么做?使用 jquery.

下面是我的代码,但没有用,

$(".start_date").datepicker({
    onSelect: function (dateText) {
        var date = dateText, y = date.getFullYear(), m = date.getMonth();
        var lastDay = new Date(y, m + 4, -2);
        $('.end_date').datepicker("setDate", lastDay);

    }
});

1:

通过 jquery 你可以试试下面的答案

$(document).ready(function() {
var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
 $('.start_date').datepicker({
  format: 'MM dd,yyyy',
  autoclose: true
});

$('.start_date').datepicker().on(
      'change',
      function() {
       var comDate = $(this).val().split(' '); 
       var newmonth = months.indexOf(comDate[0]) + 3;
       var dayyear = comDate[1].split(',');
       // var newmonth = parseInt(comDate[1]) + 2;
        var newStart = new Date(dayyear[1], newmonth, dayyear[0]);
       
        $('.end_date').datepicker({
            startDate : newStart,
            format: 'MM mm,yyyy',
              autoclose: true
        });
        
         $('.end_date').val(months[newStart.getMonth()]+ ' '+newStart.getDate()+','+newStart.getFullYear());
   });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>

 <div class="container">
 

    <div class="row">
   
        <div class="col-sm-6">
            <div class="input-group date">
      <input type="text" id="card_form_plan_start_date" class="form-control timepicker start_date" name="card_form_plan_start_date"> <input type="text" id="card_form_plan_end_date" class="form-control timepicker end_date" name="card_form_plan_end_date">
                <div class="input-group-addon">
                    <span class="glyphicon glyphicon-th"></span>
                </div>
            </div>
        </div>
    </div>


</div>