I’m trying to put a leap year checker in my Age calculator. It worked for sometime and now it outputs "This is a leap year" every time I select a date. What am I doing wrong?? Thank you!
var year;
function ageCalculator() {
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
if (userinput == null || userinput == '') {
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
} else {
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
calYear();
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
return document.getElementById("result").innerHTML =
"Age is: " + age + " years. ";
}
}
function calYear() {
var yr = year;
var yr = document.getElementsByName("year");
if (yr % 400 == 0 || (yr % 100 != 0 && yr % 4 == 0)) {
window.alert("This is not leap!");
} else {
window.alert("This is a leap!");
}
}
<input type="text" id="DOB" />
<button type="button" onclick="ageCalculator()">Calculate</button>
<span id="message"></span><br/>
<span id="result"></span>
Important:
notice that if user DOB is "2000-02-29", only the "2001-03-01" will show 1y – such depends on
I suggest you look at this version
Calculate age given the birth date in the format YYYYMMDD
To fix YOUR code we need to pass the year to the function and not try to use a non-existing year field
If there was such a field, you could access its value with
document.querySelector("[name=year]").value
since document.getElementsByName is a collection and the value would bedocument.getElementsByName("year")[0].value
So what did I do?
I tested with 2000-02-29 and 2001-02-28
NOTE the script ALSO works with 02/29/2016 but not with 29/02/2016 (European format)
this is function to check if this year is leap year
EDIT:
so the problem is in document.getElementsByName("year")
i think you should have a HTML named year which is have the year value
Here’s another Method I can make sure it will works