JQuery datepicker: Limit date from selectedDate
I would like to restrict my calendar so that users can restrict the date range.
For example: if the user selects March 10, 2014 in the From field, the user should not select after June 10, 2014 in the To section.
Here is the code I made:
Thanks in advance.
$(function() {
$( "#from" ).datepicker({
maxDate: 0,
dateFormat : 'dd-mm-yy',
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
var date = $(this).datepicker('getDate');
var maxDate = new Date(date.getMonth() + 3);
$( "#to" ).datepicker( "option", "maxDate", maxDate );
}
});
$( "#to" ).datepicker({
maxDate: 0,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
}
+3
source to share
3 answers
You can get the month with From datepicker and in 3 month increments for maxDate of the datepicker.
$("#from").datepicker({
dateFormat: "dd-M-yy",
minDate: 0,
onSelect: function (date) {
var date2 = $('#from').datepicker('getDate');
date2.setMonth(date2.getMonth() + 3);
$('#to').datepicker('setDate', date2);
$('#to').datepicker('option', 'maxDate', date2);
}
});
$('#to').datepicker({
dateFormat: "dd-M-yy",
onClose: function () {
var from = $('#from').datepicker('getDate');
console.log(from);
var to = $('#to').datepicker('getDate');
if (to <= from) {
var minDate = $('#dt2').datepicker('option', 'minDate');
$('#from').datepicker('setDate', minDate);
}
}
});
Check out this fiddle:
+1
source to share
The problem has to do with how you use dates. Please check fiddle
You need to parse the date to a valid format before assigning it to the maxDate parameter or minDate to the datepicker parameter:
var arr = selectedDate.split("-");
var date = new Date(arr[2] + "-" + arr[1] + "-" + arr[0]);
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var minDate = new Date(y, m + 1, d);
$("#to").datepicker("option", "minDate", minDate);
//var date = $(this).datepicker('getDate');
var maxDate = new Date(y, m + 3, d);
$("#to").datepicker("option", "maxDate", maxDate);
The same goes for the other datepicker:
var arr = selectedDate.split("-");
var date = new Date(arr[2] + "-" + arr[1] + "-" + arr[0]);
$("#from").datepicker("option", "maxDate", date);
Hope it helps.
0
source to share
$(function() {
$( "#to").datepicker();
$( "#from").datepicker({
maxDate: 0,
dateFormat : 'dd-mm-yy',
onSelect: function( selectedDate ) {
$( "#to").datepicker("setDate", selectedDate);
$( "#to").datepicker( "option", "minDate", selectedDate );
var date = $(this).datepicker('getDate');
var maxDate = date.setMonth(date.getMonth() + 3);
$( "#to" ).datepicker( "option", "maxDate", maxDate );
}
});
-2
source to share