I want to create a program to determine whether a given year is a leap year in the Gregorian calendar. In the HTML file I created an <input> with an id, but i can't get the value in JS. Could you explain what is the problem?
let year = document.getElementById("year").value;
function checkLeapYear(year) {
if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
console.log(year + ' is a leap year');
} else {
console.log(year + ' is not a leap year');
}
}
checkLeapYear(year);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js"></script>
</head>
<body>
Enter a year: <input type="text" id = "year">
<input type="button" id="button" onClick="checkLeapYear()" value="Check Leap Year">
</body>
</html>
yearvariable is set (in memory) to the input value (which is empty), and when entering data and pushing the button, the functioncheckLeapYearis run, but year is still empty at the time (because it is read from memory). So as @lucumt has shown, you need to get the updated input value when running the function.