Ben Rodgers
Ben Rodgers

Reputation: 21

Javascript if statement not executing 2nd parameter

I have a var that is either 1 or 0, if it's 1 the page should go to cnn.com if it's 0 it should go to google.com. Problem is, when it's 1 or 0 it always goes to google.com. Check out the running version at http://jsbin.com/ucovef/7 Thanks in advance

function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random()
}
function check_random(){
if (randomnumber = 0){
this.location.href ="http://www.cnn.com";
}
if (randomnumber = 1){
this.location.href="http://www.google.com";
}
} 

Upvotes: 2

Views: 233

Answers (4)

Dan
Dan

Reputation: 1888

You have to use == to make a check. = sets the value instead of evaluating it. I would also suggest passing the random number to the function.

function random(){
    var randomnumber=Math.floor(Math.random()*2)
    document.getElementById('random').innerHTML=(randomnumber);
    check_random(randomnumber)
}

function check_random(randomnumber){
    if (randomnumber == 0){
        this.location.href ="http://www.cnn.com";
    }
    else if(randomnumber == 1){
        this.location.href="http://www.google.com";
    } 
}  

Upvotes: 2

Molecular Man
Molecular Man

Reputation: 22386

Ben, you are using local variable from random in check_random. This won't work. Try this

function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random(randomnumber)
}
function check_random(n){
if (n == 0){
this.location.href ="http://www.cnn.com";
}
if (n == 1){
this.location.href="http://www.google.com";
}
} 

Upvotes: 0

Tomas
Tomas

Reputation: 59495

You must use == not = !!!!!!!!!!!!!!!!

Upvotes: 1

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

You need:

if (randomnumber == 0)

And:

if (randomnumber == 1)

Expressions randomnumber = 0 and randomnumber = 1 are assignment expressions that assign numbers 0 and 1 to the variables, despite them being inside an if conditional statement.

So, it always goes to google.com because everything not equal to 0 is a true expression in JavaScript.

Upvotes: 4

Related Questions