Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't access HTML value in JavaScript

I want to create a program to determine whether a given year is a leap year in the Gregorian calendar.

<!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>

In html file I created an 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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading