views:

125

answers:

3

I am writing some jQuery code that involves jumping from several functions. In one function, an 'if'-statement is used to select where the code will go next. The condition for the if statement is the value of a variable that was passed from the previous function. So, to clarify, a function passes a variable to another function, which then goes to another function which is chosen based on the function it originated from.

Here is my code in JSFiddle: http://jsfiddle.net/VFVk7/

As you can see, when you click on any of the buttons, it goes to all of the optional functions from the If-statement, not just one. Does anyone know why this is happening? Thanks very much!

+10  A: 

By writing if(origin = 'go1'), you are assigning 'go1' to the origin variable, and passing the result of that assignment (which is the string 'go1') to the if statement.
Since all non-empty strings are "truthful" in Javascript, this is equivalent to if (true), and all of the if statements execute.

You need to compare 'go1' to the origin variable by writing if (origin === 'go1').

Summary

  • The = operator assigns a value to a variable
  • The == operator performs a loose comparison (eg, true == '1', 8 == '8', 16 == '0x10', false == []).
  • The === operator performs a strict comparison. (none of the above examples are true with ===)
SLaks
Guess who feels stupid! Me...thanks SLaks!
Ben
tested working!
rockinthesixstring
Thanks very much for all the clarification SLaks!
Ben
+6  A: 

You have code like

if(origin = 'go1')

which assigns 'go1' to variable origin (and check if that's "true" -- which it is).
Try, instead:

if(origin == 'go1')

to compare instead of assigning.

Alex Martelli
A: 

Common problem. In Java it will give a compile error, in Javascript it will work just fine, probably not in the way you want it. = sign in Javascript does not perform equality operation.

fastcodejava
This is not a useful answer.
SLaks