Javascript leap year program not working

I’m trying to make a JS program in which a user enters a year and the program checks if it’s a leap year or not. But it’s showing ‘not a leap year’ for any input I give.
Here is the HTML:

<input type = "text" id="year-enter">
<button type = "submit" id="year-submit"> Submit </button>
<p style = "color:white;" id="leap"></p>

Here is the JS:

var value = parseInt(document.getElementById('year-enter').value,10);
function check_year(year){
var leap_check =document.getElementById('leap');
if(year%4!=0){
  leap_check.textContent = "It is not a leap year";
}
else if(year%100!=0){
  leap_check.textContent = "It is a leap year";
}
else if(year%400!=0){
  leap_check.textContent = "It is not a leap year";
}
else{
  leap_check.textContent = "It is a leap year";
}
}
var btn = document.getElementById('year-submit');
btn.addEventListener('click',function(){
check_year(value);
},false);

For example if I give the input as 2012 it says not a leap year.

if(year%4!=0)

The program is doing exactly what you’re asking of it, but are you asking the right questions?

When I input 2012, it’s exactly divisible by 4, so the modulus should be zero, should it not? So shouldn’t it show that it is a leap year? I’m new to JS and it’s taking me time to understand so your help would be greatly appreciated.

Yes, that’s exactly right. But is that what you’re asking in code? Review how to check equality.

Here’s what I think I did.
I changed the input given from String to integer using parseInt. Then I checked if it is exactly divisible by 4. If it is, then it should move on right? And I also tried using ‘!==’ but the result does not change…

EDIT: sorry, misread the code there. That should work fine, but what @camperextraordinaire said, you’re passing something in that isn’t what you think it is.

Also, you’re not making things easy for yourself separating out the conditions: put the entire check in one: if that’s true, it’s a leap year; if not, it isn’t.

It says null for both. I don’t understand why?

Value is null as well… I don’t understand why… I put in something in the text box and then converted it to integer. Why is it showing null?

Value should be outside right? As we are making the function parameter equal to value. And I did put it inside the function and then there’s no output

I’m sorry.Here it is:
https://codepen.io/AKSD1411/pen/varKzP

And now, it shows no output. This is happening in a lot of programs I’m writing. I don’t know why.

Hi, @AKSD1411 According to the Chrome Inspector:
On line 21 you have an error: value is not defined.

I think this has to do with function scopes.

Yes… I didn’t understand it at the time. It now works!! Thanks so much!

I had to put the value variable in the callback function and it works. Appreciate the help though :slight_smile:

Glad you got it to work.

1 Like