Reputation: 583
I have two input boxes in the first input box user select date and in second input box the date that should come for selection must be 2 days from that selected day, here is the snippet of code
$(function() {
var checkIn = $("#date-1"); var checkOut = $("#date-2");
var todayDate = new Date();
checkIn.datepicker({
dateFormat:"dd-mm-yy",
changeMonth:true,
changeYear:false,
minDate:todayDate
});
checkIn.on("change",function() {
var select = checkIn.datepicker("getDate") ;
var checkOutDate = select;
checkOut.datepicker('option','minDate',checkOutDate);
checkOut.datepicker('option','maxDate',"+2d");
});
checkOut.datepicker({
dateFormat:"dd-mm-yy",
changeMonth:false,
changeYear:false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<form>
<input type="text" id="date-1" placeholder="Date 1">
<input type="text" id="date-2" placeholder="Date 2">
</form>
The problem is it doesn't set the date when the month is changed with some different date i have also tried this
checkOut.datepicker('option','maxDate',checkOutDate);
But it doesn't work either i know i am missing some parameter but what is it ?
Upvotes: 0
Views: 140
Reputation: 4510
It's because the "+2d"
param calculates the diff from now, not from its current value. So in your example, you order to datepicker
to show a range between the selected date and now + 2 days. So you get a negative gap => no range displayed. Here a solution :
$(function() {
const checkIn = $("#date-1");
const checkOut = $("#date-2");
const todayDate = new Date();
checkIn.datepicker({
dateFormat: "dd-mm-yy",
changeMonth: true,
changeYear: false,
minDate: todayDate,
});
checkOut.datepicker({
dateFormat: "dd-mm-yy",
changeMonth: false,
changeYear: false,
});
checkIn.on("change", function() {
const checkOutDate = checkIn.datepicker("getDate");
const diffDate = checkOutDate - todayDate
const fromNow = Math.ceil(diffDate / 1000 / 60 / 60 / 24);
checkOut.datepicker("option", {
minDate: fromNow,
maxDate: fromNow + 2,
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<form>
<input type="text" id="date-1" placeholder="Date 1">
<input type="text" id="date-2" placeholder="Date 2">
</form>
Upvotes: 1