1

I need help with this simple issue. Whenever I activate the code below, I always get the result from else, no matter my input. I want to check if the day is between 1 and 30 inclusive, and if it is activate whatever is inside the if function. If it's not between 1 and 30, I want to run the else function and display the error message.

var day;
    function changePage(){
        if(day < 30 && day > 1){
           day = document.getElementById("inputBox").value;
           console.log(day);
           window.location.href = "day-" + day + ".html";}
        else{
           alert("Invalid entry, must be between 1 and 30");}}
2
  • 2
    where do you assign day value? Commented Jul 11, 2017 at 10:45
  • 1
    day === undefined so it's not between 1 and 30. Commented Jul 11, 2017 at 10:47

3 Answers 3

2

Your day isn't set until you hit the loop. You need to define day either outside or within the function but before the loop

function changePage() {
    var day = document.getElementById("inputBox").value;
    if (day < 30 && day > 1) {
        console.log(day);
        window.location.href = "day-" + day + ".html";
    } else {
        alert("Invalid entry, must be between 1 and 30");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

DUUUUUH! Thank you.
Not a problem @Mishapopkin we all make those mistakes ^_^
0

I always get the result from else

Yes it's logical because day in your code is undefined so the following if statement if(day < 30 && day > 1) will be always false so the else part will be always reached.

In your deaclartion initialize the day variable, like this:

var day = document.getElementById("inputBox").value;

Comments

0

Yes I understand, I defined day inside my function. I changed it to outside the if else function and it worked. Thank you everyone.

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.