Reputation: 109
I have Javascript code following below and could not get alert message why? How can I fix this? Thanks for all response.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="date" id="mydate">
<p id="current"></p>
<script>
document.getElementById('myDate').onchange = function () {
var selectedDateFromCalendar = this.value;
var currentdate = new Date();
document.getElementById("current").textContent = currentdate.toUTCString();
// get difference in milliseconds
var Diff = Math.abs(currentdate.getTime() - selectedDateFromCalendar.getTime());
// Convert it into days
var diffDays = Math.ceil(Diff / (1000 * 3600 * 24));
alert(diffDays);
}
</script>
</body>
Upvotes: -1
Views: 51
Reputation: 48600
You need to listen to the oninput
event. You could also check for onchange
and other events. This post is helpful.
Also, the date <input>
has a valueAsDate
property that returns a date object.
Note: I used console.log
rather than alert
, because the Stack snippets do not allow alert
.
document.getElementById('myDate').oninput = function() {
var selectedDateFromCalendar = this.value;
var currentdate = new Date();
document.getElementById("current").textContent = currentdate.toUTCString();
// Get difference in milliseconds.
var diff = Math.abs(currentdate.getTime() - this.valueAsDate.getTime());
// Convert it into days.
var diffDays = Math.ceil(diff / (1000 * 3600 * 24));
console.log(diffDays);
}
<input type="date" id="myDate" />
<p id="current"></p>
Upvotes: 1
Reputation: 516
I have added your code a little bit and it is working perfectly
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="date" id="mydate" onchange="dates()">
<p id="current"></p>
<script>
function dates () {
var selectedDateFromCalendar = this.value;
var currentdate = new Date();
document.getElementById("current").textContent = currentdate.toUTCString();
// get difference in milliseconds
var Diff = Math.abs(currentdate.getTime() - (new Date()).getTime());
// Convert it into days
var diffDays = Math.ceil(Diff / (1000 * 3600 * 24));
alert(diffDays);
}
</script>
</body>
</html>
Upvotes: -1