0

I'm using a bootstrap-datepicker widget. I have two datepickers on my page, one for start date and one for end date. I need to restrict selecting dates in a way that start date goes after end date and vice versa. So I'm adding a logic for startDate and endDate properties to these datepickers:

$(document).ready(function () {
    $('#txtEndDate').datepicker({
        startDate: new Date($("#txtStartDate").val()),
        orientation: "bottom auto"
    });
    $('#txtStartDate').datepicker({
        endDate: new Date($("#txtEndDate").val()),
        orientation: "bottom auto"
    });
    $('#txtEndDate').change(function() {
        $('#txtStartDate').datepicker({
            endDate: new Date($(this).val())
        });
    });
    $('#txtStartDate').change(function() {
        $('#txtEndDate').datepicker({
            startDate: new Date($(this).val())
        });
    });
});

It works fine only on page load, but if one of the dates is changed and not saved yet, the other datepicker is not updated immediately according this changes, and I am able to select inappropriate date in it. The available dates in that datepicker are updated only after i save changes and the whole page refreshes.

What should I add here in order to update available dates in my datepickers dynamically?

Kumar_Vikas
  • 837
  • 7
  • 16
BohdanZPM
  • 695
  • 2
  • 10
  • 22

2 Answers2

0

I already figured this out. This worked for me:

$(document).ready(function () {
    var startDate = $("#txtStartDate").val();
    var endDate = $("#txtEndDate").val();
    $('#txtEndDate').datepicker({
        beforeShowDay: function(date){
            if (startDate) {
                return new Date(startDate).getTime() <= date.getTime();
            } else {
                return true
            }
        }
    }).on("changeDate",function() {
        $('#txtStartDate').datepicker('setEndDate', $(this).val());
    });
    $('#txtStartDate').datepicker({
        beforeShowDay: function(date){
            if (endDate) {
                return new Date(endDate).getTime() >= date.getTime();
            } else {
                return true;
            }
        }
    }).on("changeDate",function() {
        $('#txtEndDate').datepicker('setStartDate', $(this).val());
    });
});
BohdanZPM
  • 695
  • 2
  • 10
  • 22
0

ADDING DAYS TO DATEPICKER

This is better, to have an array of days and adding them dinamically to datepicker using JQUERY, MOMENTJS

var availableDates = ["02-01-2020","03-01-2020","04-01-2020","05-01-2020","06-01-2020"];

function available(date) {
  dayCustom = moment(date).format('DD-MM-YYYY');
  var valid = availableDates.includes(dayCustom)?false:true;/* false/true inverse days available */
  var _tooltip = valid ? '' : 'YA SELECCIONADO';
  return [valid, "",_tooltip];
}

$('#date').datepicker({ beforeShowDay: available });