I am not able to use the .getTime() method, can someone help me? Error message in link! The original date is just from basic html date input.
JS:
document.getElementById("lastMenDate").addEventListener("change", function () {
var inputMen = this.value;
var lastMenDate = new Date(inputMen);
console.log(lastMenDate);
});
document.getElementById("targetDate").addEventListener("change", function () {
var inputTar = this.value;
var targetDate = new Date(inputTar);
console.log(targetDate);
});
document.getElementById("calc").addEventListener("click", function () {
var timeDifference = targetDate.getTime() - lastMenDate.getTime();
var daysDifference = timeDifference / (1000 * 24 * 60 * 60);
console.log(daysDifference);
});
CodePudding user response:
as commented, your vars are not scoped to the window / "all functions", so you can just assign your variable to the window/global and reference it that way. You could also look at creating an object which employs the calculation.
document.getElementById("lastMenDate").addEventListener("change", function () {
var inputMen = window.inputMen = this.value;
var lastMenDate = window.lastMenDate = new Date(inputMen);
console.log(lastMenDate);
});
document.getElementById("targetDate").addEventListener("change", function () {
var inputTar = window.inputTar = this.value;
var targetDate = window.targetDate = new Date(inputTar);
console.log(targetDate);
});
document.getElementById("calc").addEventListener("click", function () {
var timeDifference = window.timeDifference = window.targetDate.getTime() - window.lastMenDate.getTime();
var daysDifference = window.daysDifference = timeDifference / (1000 * 24 * 60 * 60);
console.log(daysDifference);
});