如何更改基于第一日期选择器的第二日期选择器日期?

时间:2019-03-04 06:37:57

标签: jquery date datepicker jquery-ui-datepicker

我有两个日期选择器,分别用于开始日期和结束日期。当页面加载结束日期为当前日期后的3个月,并且开始日期为当前日期时,自动发生。

enter image description here

因此,我想更改日期选择器中的开始日期,第二个日期选择器需要自动更新。

该怎么做?使用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

1 个答案:

答案 0 :(得分:0)

通过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>