JS alert if inputted date 2 <= date 1 - javascript

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!

Related

Form validation with dates. First date must be earlier than second date input

I have been trying to find a solution for days now. I am not strong in javascript and it confuses me.
I want the submit button disabled unless the start time is earlier that the end time. I can do this so easily in PHP but I need to prevent submission of a form on the client side in this case. I was able to figure out basic numbers but not date-times. I also would like to insert a message inside of the div tags with the id of message.
<input type="datetime-local" name="start" id="start">
<input type="datetime-local" name="end" id="end">
<div id="message"></div>
<button type="submit" name="submit" id="submit">Click to Submit</button>
This should do the trick:
<input type="datetime-local" name="start" id="start">
<input type="datetime-local" name="end" id="end">
<div id="message"></div>
<button type="submit" name="submit" id="submit">Click to Submit</button>
<script type="text/javascript">
let startInput = document.getElementById('start');
let endInput = document.getElementById('end');
let messageDiv = document.getElementById('message');
let submitButton = document.getElementById('submit');
let compare = () => {
let startValue = (new Date(startInput.value)).getTime();
let endValue = (new Date(endInput.value)).getTime();
if (endValue < startValue) {
messageDiv.innerHTML = 'Start date must be before end date!';
submitButton.disabled = true;
} else {
messageDiv.innerHTML = '';
submitButton.disabled = false;
}
};
startInput.addEventListener('change', compare);
endInput.addEventListener('change', compare);
</script>
First, we store all the HTML elements we need in variables. Then we declare a function that we run whenever either date input changes. Inside that function, we check if the end date is before the start date. If it is, we display the error message and disable the submit button; if it isn't, we hide the error message and enable the submit button.
I ran this code and it works.
Comment on this answer if you have questions.
something like that ?
<form id="my-form">
<input type="datetime-local" name="start" >
<input type="datetime-local" name="end" >
<div id="message"></div>
<button type="submit" name="btSubmit" disabled>Click to Submit</button>
</form>
const myForm = document.getElementById('my-form')
myForm.end.oninput=()=>
{
let d_start = (new Date(myForm.start.value)) || Infinity
, d_end = (new Date(myForm.end.value)) || 0
myForm.btSubmit.disabled =( d_start > d_end)
}

Inputs and Outputs from/to HTML and JS

I want to get inputs from my HTML process the info in my JS and send a result back to the HTML. In the example the JS calculates the stay of a person in an accommodation. I just need to get their check-in and check-out dates.
var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
</br>
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
</br>
<span>You are staying</span><span id="stay"></span> <span> days with us.</span>
</br>
</form>
To get "Check-in date":
var inDate=document.getElementById("inDate").value;
To get "Check-out date"
var outDate=document.getElementById("outDate").value;
If you want the date picker just import jquery UI library it will allow you insert the date calendar directly
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
</br>
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
</br>
<span>You are staying</span><span id="stay"></span> <span> days with us.</span>
</br>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-git.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
</form>
</body>
</html>
Add add this follow javascript code:
$(function() {
$( "#inDate, #outDate" ).datepicker();
});
Here is the link to jsbin: https://jsbin.com/kunugi/edit?html,js,output
Read the code comments ,hope this will help
function calc() {
// get corresponding value from input
var inDate = document.getElementById('inDate').value;
var outDate = document.getElementById('outDate').value;
// allow calculations if both input fields have values, otherwise error can occur while calculating date
if (inDate && outDate) {
// convert to date format
var date1 = new Date(inDate);
var date2 = new Date(outDate);
// code for checking date1 > date 2 if you want
//calculations
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//for Displaying in html
document.getElementById('stay').innerHTML = diffDays;
}
}
// adding event so that when we change any one of the field, the functuion will calculate the daydiff and display in the html page
document.getElementById('outDate').addEventListener("change", calc);
document.getElementById('inDate').addEventListener("change", calc);
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
<span>You are staying </span><span id="stay"></span> <span> days with us.</span>
</form>

javascript function not working with my html form

i have an html code for a form and a javascript function that will perform age calculation and populate it in the next page but the calculation is not working. every other field in the form in being displayed in the next page but the calculation is not just working.
<!DOCTYPE html>
<html>
<body>
<script src="text/javascript">
function calculate_age(birth_month,birth_day,birth_year)
{
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
today_day = today_date.getDate();
age = today_year - birth_year;
if ( today_month < (birth_month - 1))
{
age--;
}
if (((birth_month - 1) == today_month) && (today_day < birth_day))
{
age--;
}
return age--;
document.getElementById("myForm").innerHTML = window.calculate_age()
}
</script>
<form action="new1.php" method="post" id="myForm">
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br>
Date of Birth:<br>
<input type="date" name="age" id="dob" script="calculate_age">
<br><br>
<input type="submit" onclick="calculate_age(birth_month,birth_day,birth_year)" value="Submit">
</form>
</body>
</html>
return age--;
document.getElementById("myForm").innerHTML = window.calculate_age()
The statement that makes modification to your DOM element is never reached.
the first answer is absolutely right. additionally, your button's type is "submit". so, when you click that button, first it runs the function, then posts the page, and all your values are lost because the function that calculates age doesn't run after the form is submitted. you have to change the button's type or run the function on window onload. besides, the function that calculates age have compilation errors. the part that changes the innerhtml of the form needs ";" at the end

Difference between two dates from user input moment js

This is my form:
<form>
<input type="text" placeholder="Check in date" id="checkin" />
<input type="text" placeholder="Check out date" id="checkout" />
<input type="submit" onclick="result()" id="submit" />
</form>
And this is my javascript for calculating the money=days*price
<script language="javascript" type="text/javascript">
function result()
{
var a = document.getElementById("checkin").value;
var b = document.getElementById("checkout").value;
var checkin = moment(a).format('DD-MM-YYYY');
var checkout = moment(b).format('DD-MM-YYYY');
var days= checkout.diff(checkin, 'days');
var price=100;
alert("The money you have to pay is: "+days*price);
}
</script>
This is my test case:
checkin date = 05-12-2014,
checkout date = 25-12-2014
When I click submit, nothing happens.
Can anyone please explain to me why and how can I fix this. Thank you!
function result(e) //e refers to event.
{
e.preventDefault();
var a = document.getElementById("checkin").value;
var b = document.getElementById("checkout").value;
var checkin = moment(a, 'DD-MM-YYYY');
var checkout = moment(b, 'DD-MM-YYYY');
var days= checkout.diff(checkin, 'days');
var price=100;
alert("The money you have to pay is: "+days*price);
}
<script src="http://momentjs.com/downloads/moment.js"></script>
<form>
<input type="text" placeholder="Check in date" id="checkin" />
<input type="text" placeholder="Check out date" id="checkout" />
<input type="submit" onclick="result(event)" id="submit" />
</form>
First of all you're submitting the form. You need to prevent that using event.preventDefault(). I think your problems will melt away after that. I strongly suggest to restrict the date inputs. Either use a library to select dates from a picker or provide the user with some guidance to the date format.
Use this to convert dates to moment dates
var checkin = moment(a, 'DD-MM-YYYY')
var checkout = moment(b, 'DD-MM-YYYY')
See the jsbin

jquery datepicker code not working (set specific date as default)

I am trying to set the date to a specific one on page load so I'm trying this code:
<script type="text/javascript">
$(document).ready(function() {
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$("input[type='submit']").click(function(e) {
e.preventDefault();
$.post("s.php", $("form").serializeArray(), function(message) {
window.location="v.php"
});
});
});
</script>
//The form part where is displays the datepicker:
<form action="#" method="POST">
<div data-role="fieldcontain">
<label for="date">Date:</label>
<input type="date" name="date" id="date" value="" />
<input type="submit" value="submit" />
</div>
</form>
The problem is that nothing's changing ... the default is still the current date :o/
Any ideas anyone please?
UPDATE: Tried this code:
var queryDate = new Date(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$('#date').val(queryDate);
And the date is appearing in the input box but the calendar is not in the right month nor date ... Moving foward but still not working.
I'm not sure sure the suggested answer here is not working. As I have tested it display on the right month and year, but only not highlighted the date. This could be because the date format.
Try adding this code to have a default value on your date.
$('#date').val(queryDate);
Then you may see that the format is different with the date in date-picker. If you manage to set the right format with date-picker, you get the things you wanted.
Umm what if you tried this
new Date(year, month, day, hours, minutes, seconds, milliseconds)
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
Then the datepicker knows its a date object and how to handle it.
EDIT
Ok - all i did was copy the code exactly as you got it here several posts the same suggestion- and the code you edited. Added tags- inlcuded jquery and jquery ui..
I see no problem- the defuatl date is 2009.
</head>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$("input[type='submit']").click(function(e) {
e.preventDefault();
$.post("s.php", $("form").serializeArray(), function(message) {
window.location="v.php"
});
});
});
</script>
</head>
<body>
//The form part where is displays the datepicker:
<form action="#" method="POST">
<div data-role="fieldcontain">
<label for="date">Date:</label>
<input type="date" name="date" id="date" value="" />
<input type="submit" value="submit" />
</div>
</form>
</body>
Result (no styles sheet attached)
Working example- tell me what is wrong
http://jsfiddle.net/ppumkin/nptgn/
Try this
var queryDate = new Date(2009,11,01);<br/>
$('#date').datepicker({defaultDate: queryDate});
I was having a similar problem, I solved it like this
$('.datepicker').datepicker({dateFormat: "yy-mm-dd", defaultDate: "+3m"} );
Try this
$('#mydate').val("2009-11-01");

Categories

Resources