Search code examples
javascriptdatepickerbootstrap-datepicker

Limit date range based on first selected date


I am using bootstrap-datepicker. I have 2 input field and I want to restrict second input for only the next 5 days from the first date after user select date from first input field.

date 1 <input type="text" class="datepicker"><br>
date 2 <input type="text" class="datepicker2"><br>

$(function(){
    $('.datepicker').datepicker({
        format: 'mm-dd-yyyy',
        autoclose: true
        }).on('changeDate', function (selected) {
            var startDate = new Date(selected.date.valueOf());

            $('.datepicker2').datepicker('setStartDate', startDate);

            $('.datepicker2').datepicker('endDate', '+5d')
        });
});

$(function(){
    $('.datepicker2').datepicker({
        format: 'mm-dd-yyyy',
        autoclose: true,
        //endDate: '+5d'
    });
});

This is currently not working. It does worked though if I put it in datepicker2 attribute. Please help and thanks in advance

Here's the code example : http://jsfiddle.net/jnh8pyst/


Solution

  • For this you must use setEndDate method and create the endDate plus x days you want, taking as a base the startDate and then use the setEndDate for the desired picker.

    let endDate = new Date(startDate);
    endDate = new Date(endDate.setDate(endDate.getDate() + 5));
    $('.datepicker2').datepicker('setEndDate', endDate);
    

    To the end you will have:

    $(function() {
    
      $('.datepicker').datepicker({
        format: 'mm-dd-yyyy',
        autoclose: true
      }).on('changeDate', function(selected) {
        let startDate = new Date(selected.date.valueOf());
        let endDate = new Date(startDate);
        endDate = new Date(endDate.setDate(endDate.getDate() + 5));
        $('.datepicker2').datepicker('setStartDate', startDate);
        $('.datepicker2').datepicker('setEndDate', endDate);
      });
    
      $('.datepicker2').datepicker({
        format: 'mm-dd-yyyy',
        autoclose: true,
      });
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.2.0/css/datepicker.min.css" rel="stylesheet" />
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.2.0/js/bootstrap-datepicker.js"></script>
    Date 1
    <input type="text" class="datepicker">
    <br> Date 2
    <input type="text" class="datepicker2">
    <br>