Reputation: 11
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");}}
Upvotes: 1
Views: 52
Reputation: 11
Yes I understand, I defined day inside my function. I changed it to outside the if else function and it worked. Thank you everyone.
Upvotes: 0
Reputation: 32145
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;
Upvotes: 0
Reputation: 3676
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");
}
}
Upvotes: 2