0

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>

2
  • The problem is that when javascript runs for the first time the year variable is set (in memory) to the input value (which is empty), and when entering data and pushing the button, the function checkLeapYear is 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. Commented Oct 29, 2022 at 8:20
  • It makes sense, thank you for explaining this ^^ Commented Oct 29, 2022 at 8:28

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.