Reputation: 4574
I am using Bootstrap Datepicker but having much difficulty preventing client from selecting an end date that is prior to the start date + vice versa (start date is after end date). I have tried a few script changes with no luck.
Wish the documentation had some better examples. It seems common that a date range should exclude this wrong selection ability.
I would also like to populate the start date when the end date is selected first. It is working but changes the desired formatting from dd mm yyy to mm dd yyyy. Be nice if it also inserted selected end date - 1 year into start date.
(function($) {
"use strict";
//INPUTS
let startDateInput = $('#date-picker-container input[name="start"]');
let endDateInput = $('#date-picker-container input[name="end"]');
//INPUT VALUES
let startDateValue = startDateInput.val();
let endDateValue = endDateInput.val();
$(startDateInput, endDateInput).datepicker({
format: "dd/mm/yyyy",
maxViewMode: 3
});
$(startDateInput).datepicker()
.on('changeDate', function(e) {
if($(endDateInput).val().length <= 0) {
$(endDateInput).datepicker('show');
$(endDateInput).val($(this).val()); //PLUS ONE DAY FROM SELECTED VALUE
}
$(this).datepicker('hide');
});
$(endDateInput).datepicker()
.on('changeDate', function(e) {
if($(startDateInput).val() <= 0) {
$(startDateInput).datepicker('show');
$(startDateInput).val($(this).val()); //MINUS ONE YEAR FROM SELECTED VALUE
}
$(this).datepicker('hide');
});
})(jQuery);
Upvotes: 3
Views: 1514
Reputation: 573
How about do something like this.
My own custom range function. You can customize it back. :)
$(document).ready(function(){
$.calendar_max_min = function(){
var ths = $(this);
var caltarget = ths.data("target");
var calcheck = ths.data("calcheck");
var calmin = $(caltarget+"[data-type='min']").prop("value");
var calmax = $(caltarget+"[data-type='max']").prop("value");
if(!calcheck){
ths.attr("data-calcheck","true");
ths.datepicker({
format: 'dd-mm-yyyy',
startDate: calmin,
endDate: calmax
});
ths.datepicker("show"); // trigger manual. because we set it after click;
}else{
ths.datepicker("destroy"); // destoy old format. and reformat option
if(ths.data("type") === "min") calmin = ''; // if the click item is the min. can change value
if(ths.data("type") === "max") calmax = ''; // if the click item is the max. can change value
ths.attr("data-calcheck","true");
ths.datepicker({
format: 'dd-mm-yyyy',
startDate: calmin,
endDate: calmax
});
ths.datepicker("show"); // trigger manual. because we set it after click;
}
};
$(".my_calendar").on("click",$.calendar_max_min);
});
And this is jsfiddle example : https://jsfiddle.net/synz/g2yohfb6/
Upvotes: 1