When I try to retrieve the value of the input field and do some math operation, I get zero or NaN as a result. Knowing that I write only numbers in the input field and use parseInt method on the retrieved value
let myInput = document.getElementById("my-input").value;
let btnMonth = document.getElementById("month");
let btnDay = document.getElementById("day");
let myResult = document.getElementById("my-div");
function ageInDays() {
return myResult.innerHTML = `Your age in Days: ${parseInt(myInput * 12 * 30)}`;
}
function ageInMonths () {
return myResult.innerHTML = `Your age in Months: ${parseInt(myInput * 12)}`;
}
btnDay.addEventListener("click", ageInDays);
btnMonth.addEventListener("click", ageInMonths);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Learn JavaScript</title>
<link rel="stylesheet" href="mystyle.css">
<style>
</style>
</head>
<body>
<div>
<input type="text" id="my-input">
<button id="day">Days</button>
<button id="month">Months</button>
</div>
<div id="my-div"></div>
<script src="mains.js"></script>
</body>
</html>
>Solution :
Get your value from the DOM within the function call, not in the global scope at the top. As it sits, your value would only get stored once. Any further change to it will not get stored. parse your input before doing math with it.
Also, don’t use innerHTML with user input. It is asecurity flaw. Use innerText instead.
let myInput = document.getElementById("my-input")
let btnMonth = document.getElementById("month");
let btnDay = document.getElementById("day");
let myResult = document.getElementById("my-div");
function ageInDays() {
return myResult.innerHTML = `Your age in Days: ${parseInt(myInput.value) * 12 * 30}`;
}
function ageInMonths() {
return myResult.innerHTML = `Your age in Months: ${parseInt(myInput.value) * 12}`;
}
btnDay.addEventListener("click", ageInDays);
btnMonth.addEventListener("click", ageInMonths);
<div>
<input type="text" id="my-input">
<button id="day">Days</button>
<button id="month">Months</button>
</div>
<div id="my-div"></div>