-5

I have two textboxes, one is arrival and another is departed. If the user tries to input for example.:

"2017-03-09" in departure and the arrival date has "2017-03-10", I want the departure value to be the same as arrival.

My code does not work at the moment for some reason.

jQuery:

function onChange(sender, txt, departed) {
    var txtArrival = $("#txtArrivalDate");
    var txtArrivalDate = $(txtArrival).val(); //Value from arrival
    var txtDate = $(txt).val(); //Value from departed

    var departureDate = new Date(txtDate); //Converting string to date
    var arrivalDate = new Date(txtArrivalDate); //Converting string to date

    if (departureDate.getTime() < arrivalDate.getTime()) {
        txt.val = txtArrivalDate; //Does not work, value is not updated
    }
}
Malphai
  • 307
  • 3
  • 6
  • 21
  • First check if dates are getting created properly. Second, to compare dates, use `date.getTime` method – Rajesh Mar 10 '17 at 08:39
  • Yes they are created properly. And why should `date.getTime` do anything different? I want the textbox value to be updated. – Malphai Mar 10 '17 at 08:39
  • compare the dates as timestamps using the `getTime()` method – Laazo Mar 10 '17 at 08:39
  • @Rajesh Can you show me what you mean? – Malphai Mar 10 '17 at 08:40
  • @Azola Create a post please. – Malphai Mar 10 '17 at 08:40
  • Possible duplicate of [Compare two dates with JavaScript](http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Rajesh Mar 10 '17 at 08:43
  • _Because of the variances in parsing of date strings, it is recommended to always **manually parse** strings as results are inconsistent_ ([ref.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)) – hindmost Mar 10 '17 at 08:46
  • @hindmost That was no useful answer at all. – Malphai Mar 10 '17 at 08:46

2 Answers2

1

Something like this ?

 function onChange(sender, txt, departed) 
 {
    var txtArrival = $("#txtArrivalDate");
    var txtArrivalDate = $(txtArrival).val(); //Value from arrival
    var txtDate = $(txt).val(); //Value from departed
    
    var departureDate = new Date(txtDate); //Converting string to date
    var arrivalDate = new Date(txtArrivalDate); //Converting string to date

    

    if (departureDate.getTime() < arrivalDate.getTime()) {
         txt.val(txtArrivalDate); //Does not work, value is not updated
    }
}

$("#txtDepartureDate").change(function(event){
  onChange(event, $("#txtDepartureDate"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="txtArrivalDate" />
<input type="date" id="txtDepartureDate" />
Brent Boden
  • 569
  • 2
  • 10
-2

is

$(txt).val(txtArrivalDate);

or

$(txt).html(txtArrivalDate);

instead of

txt.val = txtArrivalDate;

what you're trying to achieve?

Dmytro Us
  • 11
  • 4