magdy magdy - 4 months ago 16
Javascript Question

Update departure date if arrival date is greater

I want to update the departure-date in the calendar when the arrival-date is greater, using JavaScript, adding one day. This is my code but the problem is that when I change the arrival-date, departure-date remains the same.



function addDate() {
date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();

if (document.getElementById('startDate').value == '') {
document.getElementById('startDate').value = month + '/' + day + '/' + year;
}
if (document.getElementById('endDate').value == '') {
document.getElementById('endDate').value = month + '/' + (day + 1) + '/' + year;
}
}

<input type="text" id="startDate" style="background-color:#5c677b;height:25px;" name="checkin" placeholder="checkin">

<input type="text" id="endDate" style="background-color:#5c677b;height:25px;" name="checkout" placeholder="checkout">




Answer

If I got that right, you want to:

  • Set by default the current date as arrival date and the next day as departure date
  • Update the departure date when changing the arrival date only if that's greater

My solution is this. Firstly you have to catch the event, by putting a onchange="changedDate()". Then check if arrivalDate>departureDate and when true get that date and finally update the departure date with the next one.

addDate();
function addDate() {
  date = new Date();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var year = date.getFullYear();

  if (document.getElementById('startDate').value == '') {
    document.getElementById('startDate').value = month + '/' + day + '/' + year;
  }
  if (document.getElementById('endDate').value == '') {
    document.getElementById('endDate').value = month + '/' + (day + 1) + '/' + year;
  }
}
function changedDate(){
  var arrivalDate = new Date(document.getElementById('startDate').value) ;
  var departureDate = new Date(document.getElementById('endDate').value) ;
  if(arrivalDate>departureDate){
    var arrDate = new Date();
    arrDate.setDate(arrivalDate.getDate()+1);
    arrDate.setMonth(arrivalDate.getMonth()+1);
    arrDate.setFullYear(arrivalDate.getFullYear());
    document.getElementById('endDate').value = arrDate.getMonth() + '/' + arrDate.getDate() + '/' + arrDate.getFullYear();
  }
}
<input type="text" id="startDate" style="background-color:#5c677b;height:25px;" name="checkin" placeholder="checkin" onchange="changedDate()">
<input type="text" id="endDate" style="background-color:#5c677b;height:25px;" name="checkout" placeholder="checkout">