简体   繁体   中英

Bootstrap DatePicker Limit startdate dynamically

I have 2 date pickers which are used to pick the start date and return date.

I would like to limit the return date using the start date value eg if I pick 15/7/2019, then the return date should start from 16/7/2019. This should be dynamic.

I tried the following implementation:

var returndate = new Date();
returndate.setDate(returndate.getDate() + 1);
$('.travel-depature-dates').datepicker({
    autoclose: true,
    todayHighlight: true,
    startDate: returndate,
    beforeShowYear: function (date) {

    },
    toggleActive: true,
    format: 'dd/mm/yyyy',
}).on('changeDate', function (e) {
    return_datepicker();
});

function return_datepicker() {
    var departure_date = $(".departure_date").val();

    var minimum_date = new Date();
    minimum_date.setFullYear(minimum_date.getFullYear() - 1);

    console.log("Departure date => " + departure_date);


    $('.travel-return-dates').datepicker({
        autoclose: true,
        todayHighlight: true,
        startDate: departure_date,
        toggleActive: true,
        format: 'dd/mm/yyyy'
    });

}

However, the output for the return date does not apply the limit of the departure date.

How can I limit the return, start date using the value selected from the return date?

It works in two ways. In the way you asked and reverse. Enjoy

  var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var dayOfWeekNames = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); $('.d1').datepicker({format: "dd/mm/yyyy", autoclose: true}).val(formatDate(new Date())); $('.d2').datepicker({format: "dd/mm/yyyy", autoclose: true}).val(formatDate(tomorrow)); function d1_ch (){ var d1_val = convert('/',$('.d1').val()), d2_val = convert('/',$('.d2').val()); if (d1_val >= d2_val) { d2_val.setDate(d1_val.getDate() + 1); $('.d2').datepicker().val(formatDate(d2_val)); } } function d2_ch (){ var d1_val = convert('/',$('.d1').val()), d2_val = convert('/',$('.d2').val()); if (d2_val <= d1_val) { d1_val.setDate(d2_val.getDate() - 1); $('.d1').datepicker().val(formatDate(d1_val)); } } function convert(delimiter,dateString) { var splitted = dateString.split('/'); var myDate = new Date(splitted[2],splitted[1]-1,splitted[0]); return myDate; } function formatDate(date, patternStr){ if (!patternStr) { patternStr = 'dd/MM/yyyy'; } var day = date.getDate(), month = date.getMonth(), year = date.getFullYear(), hour = date.getHours(), minute = date.getMinutes(), second = date.getSeconds(), miliseconds = date.getMilliseconds(), h = hour % 12, hh = twoDigitPad(h), HH = twoDigitPad(hour), mm = twoDigitPad(minute), ss = twoDigitPad(second), aaa = hour < 12 ? 'AM' : 'PM', EEEE = dayOfWeekNames[date.getDay()], EEE = EEEE.substr(0, 3), dd = twoDigitPad(day), M = month + 1, MM = twoDigitPad(M), MMMM = monthNames[month], MMM = MMMM.substr(0, 3), yyyy = year + "", yy = yyyy.substr(2, 2) ; // checks to see if month name will be used if (patternStr.indexOf('MMM') > -1) { patternStr = patternStr .replace('MMMM', MMMM) .replace('MMM', MMM); } else { patternStr = patternStr .replace('MM', MM) .replace('M', M); } return patternStr .replace('hh', hh).replace('h', h) .replace('HH', HH).replace('H', hour) .replace('mm', mm).replace('m', minute) .replace('ss', ss).replace('s', second) .replace('S', miliseconds) .replace('dd', dd).replace('d', day) .replace('EEEE', EEEE).replace('EEE', EEE) .replace('yyyy', yyyy) .replace('yy', yy) .replace('aaa', aaa) ; } function twoDigitPad(num) { return num < 10 ? "0" + num : num; } 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet"> <input class="d1 datepicker" onchange="d1_ch();" value=""/> <input class="d2 datepicker" onchange="d2_ch();" value=""/> 

If i am right you are using bootstrap-datepicker

This link above give you the methods that are accessible on the date picker the link above shows you the 'changeDate' event that happens when you bind to datepciker and then you can use this combined with a function (i have done this in JQuery considering you are using bootstrap) to then update the date.

i have extended the method slightly to the end date of the first input is set a well. hope this helps

HTML

<form>
  <div class="row">
    <div class="col">
      <input type="text" class="form-control date" placeholder="Departure Date">
    </div>
    <div class="col">
      <input type="text" class="form-control date" placeholder="Return Date">
    </div>
  </div>
</form>

JS

$("input[type='text']").datepicker({
        autoclose: true,
    todayHighlight: true,
    toggleActive: true,
    format: 'dd/mm/yyyy',
}).on('changeDate', function(selected){
  updateDate($(this).closest('form').find('input:text'), selected);
});

function updateDate(inputs, selected){
   var minDate = new Date(selected.date.valueOf());
   $(inputs[1]).datepicker('setStartDate', minDate);
   $(inputs[0]).datepicker('setEndDate', minDate);
}

JSFIDDLE

Detailed Explanation

  1. Using the JQuery selector if get all the inputs($("input[type='text']")). This creates an array of element on the page.
  2. Set up the datepickers default initialization values.
  3. Chain the '.on('changeDate'' method so that anytime and input it's date changed then this will run.
  4. Using '$(this).closest('form').find('input:text')' i get the inputs to use as sectors later.
  5. The function(selected) passes the value input into the method then i use the accessorss 'selected.date.valueOf()' to return that date's value.
  6. Finally set the date using 'setStartDate' on the element index from my array.

The following example uses d/m/Y date format. It checks the following:

  1. Start date starts automatically from today.
  2. End date starts automatically from tomorrow.
  3. If End date is picked less than Start date then it automatically changes Start date and visa versa.
let TODAY="01/10/2022";
let TOMORROW="02/10/2022";
let DATE_FORMAT="dd/mm/yyyy";

function setNextDayForFEnd(selected)
{
    let nextDate = new Date(selected.date.valueOf());
    nextDate.setDate(nextDate.getDate() + 1);
    fend.datepicker('setDate', nextDate);
}

function setPrevDayForFEnd(selected)
{
    let prevDate = new Date(selected.date.valueOf());
    prevDate.setDate(prevDate.getDate() - 1);
    fstart.datepicker('setDate', prevDate);
}

function retrunFormatted()
{
    let start = fstart.val().split('/');
    let end = fend.val().split('/');
    start = new Date(parseInt(start[2]), parseInt(start[1])-1, parseInt(start[0]));
    end = new Date(parseInt(end[2]), parseInt(end[1])-1, parseInt(end[0]));
    return [start, end];
}

let fstart = $('#fstart');
let fend = $('#fend');
if (fstart.length > 0) {
    fstart.datepicker({
        format: DATE_FORMAT,
        startDate: TODAY,
        todayBtn: 'linked',
        todayHighlight: true,
        autoclose: true
    }).on('changeDate', function(selected){
        if (fend.val() === '') {
            // Auto set next day
            setNextDayForFEnd(selected);
        } else {
            // Auto set next day if start date is in past
            let dateRange = retrunFormatted();
            if (dateRange[0].getTime() >= dateRange[1].getTime()) {
                setNextDayForFEnd(selected);
            }
        }
    });
    fend.datepicker({
        format: DATE_FORMAT,
        startDate: TOMORROW,
        todayBtn: 'linked',
        todayHighlight: true,
        autoclose: true
    }).on('changeDate', function(selected){
        if (fstart.val() === '') {
            // Auto set next day
            setPrevDayForFEnd(selected);
        } else {
            // Auto set next day if start date is in past
            let dateRange = retrunFormatted();
            if (dateRange[0].getTime() >= dateRange[1].getTime()) {
                setPrevDayForFEnd(selected);
            }
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM