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>
CodePudding user response:
The reason is that let year = document.getElementById("year").value;
is outside the checkLeapYear()
and we have not input any value for it when this line executed
In order to solve it,you need to put year
inside checkLeapYear()
so that each time you can get the latest input value,also there is no need for checkLeapYear(year);
since we have add onClick="checkLeapYear()"
function checkLeapYear() {
let year = document.getElementById("year").value;
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');
}
}
<!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>