Reputation: 123
So I have 3 different inputs for the user - Day/Month/Year, and I'm trying to run an if statement to check if the month is Jan/Feb (1 or 2), and then if it subtracts 1 from the year. My if statement is:
if (month == 1 || month == 2) {
if (month == 1) {
year = Number(year) - 1;
}
else if (month == 2) {
year = Number(year) - 1;
}
}
This is my first time trying to use javascript and it's very frustrating!
As you can see my code runs when I have month = 3, but as soon as I change it to 1 or 2 it no longer executes...
Upvotes: 5
Views: 664
Reputation: 61
I've just try it on JSFidddle
$(document).ready(function(){
var month=1;
var year ='2018';
if ((month == 1) || (month == 2)) {
if (month == 1) {
year = Number(year) - 1;
}
else if (month == 2) {
year = Number(year) - 1;
}
}
alert(year);
});
Upvotes: -1
Reputation: 207557
It fails because you convert the year to a string and than after than you use string operations on the number. The error in your console should clearly state it.
year = Number(year) - 1
...
var century = year.substring(0,2)
so if you are going to do string actions on it, than you need to convert the number back to a string.
So either you do
year = (Number(year) - 1).toString()
or
var century = year.toString().substring(0,2)
In the end, the error "Uncaught TypeError: year.substring is not a function" should have been in your developer console.
Upvotes: 4