5

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... enter image description here

11
  • 4
    Post code instead of images Commented Dec 6, 2018 at 17:48
  • 3
    Post your code as text not images. Commented Dec 6, 2018 at 17:48
  • 2
    Or better yet put the code in the second screenshot into a Stack Snippet Commented Dec 6, 2018 at 17:50
  • 3
    @mahlatse and when question is edited, downvotes can be altered... Commented Dec 6, 2018 at 17:51
  • 1
    @mahlatse if there is an edit, you can change your vote. Commented Dec 6, 2018 at 17:53

2 Answers 2

4

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.

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

Comments

-1

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);
});

JSFIDDLE LINK

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.