简体   繁体   中英

JS alert if inputted date 2 <= date 1

I have a form where a visitor can make a lodging reservation with an arrival date and departure date. If they click on an input field a calendar pops up for them to select a date. How can I add a popup JS alert if the departure date is <= the arrival date? My code is as follows:

<head>
...
<script type="text/javascript" src="js/CalendarPopup.js"></script>
<script type="text/javascript">document.write(getCalendarStyles());</script>
...
</head
    <script type="text/javascript" id="jsArrive">
var now = new Date();
var yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
var calArrive = new CalendarPopup("divArrive");
</script>
<b>Arrive:</b>
<input type="text" name="dateArrive" value="" size="15" onClick="calArrive.select(document.forms[0].dateArrive,'dateArrive','d/M/yyyy'); return false;" title="calArrive.select(document.forms[0].dateArrive,'dateArrive','d/M/yyyy'); return false;" id="dateArrive" />
</p>
<div id="divArrive" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>

<script type="text/javascript" id="jsDepart">
var now = new Date();
var yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
var calDepart = new CalendarPopup("divDepart");
</script>
<b>Depart:</b>
<input type="text" name="dateDepart" value="" size="15" onClick="calDepart.select(document.forms[0].dateDepart,'dateDepart','d/M/yyyy'); return false;" title="calDepart.select(document.forms[0].dateDepart,'dateDepart','d/M/yyyy'); return false;" id="dateDepart" />
<input type="submit" value="Go" name="submit"  />
</p>
<div id="divDepart" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>

It's as simple as comparing the two dates, like so:

if (departureDate <= arrivalDate) {
   alert ("You must make sure your departure is before your arrival!);
} 

I suggest you run the above if statement when the user has entered there arrival date. So you'd use an onChange event on each of the inputs incase they go back and change there departure date!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM