-->

Bootstrap datepicker change minDate/startDate from

2019-01-18 06:13发布

问题:

There are two datepickers in my page and both are of bootstrap. The condition is only that Start date never High with respect to End Date. Means End date Attribute (minDate) must be changed when Start Date changed by datepicker and same when End Date Changed, the minrange of calendar of Start Date datepicker should be according to End Date Value.

I hope you understand my problem

$(document).ready(function(){
  
      $("#startdate").datepicker({
       
        todayBtn:  1,
        autoclose: true,
       
       
      }).on('changeDate', function (selected) {
        var minDate = new Date(selected.date.valueOf());
        $('#enddate').datetimepicker('setStartDate', minDate);
    });
    
        $("#enddate").datepicker();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">



<input type="text" placehoder="Start Date" id="startdate"/>
<input type="text" placehoder="End Date" id="enddate"/>

回答1:

I have made a jsfiddle doing what you want. As pqdong commented you were calling datetimepicker instead of datepicker when setting end date.

Here is the working javascript:

$(document).ready(function(){

    $("#startdate").datepicker({
        todayBtn:  1,
        autoclose: true,
    }).on('changeDate', function (selected) {
        var minDate = new Date(selected.date.valueOf());
        $('#enddate').datepicker('setStartDate', minDate);
    });

    $("#enddate").datepicker()
        .on('changeDate', function (selected) {
            var maxDate = new Date(selected.date.valueOf());
            $('#startdate').datepicker('setEndDate', maxDate);
        });

});


回答2:

I don't have enough reputation tocomment on Razzildinho's excellent answer, but did want to offer one small addition that will help users, which is to highlight the selected day on the second datepicker. You can do this by adding this line:

$('#enddate').datepicker('setDate', minDate);

So in context it will look like this:

$(document).ready(function(){

$("#startdate").datepicker({
    todayBtn:  1,
    autoclose: true,
}).on('changeDate', function (selected) {
    var minDate = new Date(selected.date.valueOf());
    $('#enddate').datepicker('setStartDate', minDate);
    $('#enddate').datepicker('setDate', minDate); // <--THIS IS THE LINE ADDED
});

$("#enddate").datepicker()
    .on('changeDate', function (selected) {
        var maxDate = new Date(selected.date.valueOf());
        $('#startdate').datepicker('setEndDate', maxDate);
    });

});