views:

88

answers:

7

Quick question, I'm trying to pass a value to a variable and then run a function if the variable was set to something specific. How do I do that?

I have the following example where I want to assign the value name to a form field if the variable type is set to 1.

function test(name,type) {
  if (type=1) {
    document.myform.name.value = name;
  }
}

and a link in the body of the html:

<a href="javascript:test('myname','1');">FILL IN MY NAME</a>

I also tried the following with no luck:

function test(name,type) {
  var checktype = type;
  if (checktype = 1) {
    document.myform.name.value = name;
  }
}

I'm pretty sure something like this is possible, just not sure what I'm doing wrong.

+3  A: 

Try this:

function test(name,type) {
  var checktype = type;
  if (checktype == 1) {
    document.myform.name.value = name;
  }
}

You were missing ==

Sarfraz
+1... 41 seconds faster...
Sani Huttunen
@Sani Huttunen: Thanks :)
Sarfraz
+2  A: 

You want to use ==, not =. Using a single symbol will assign the value of 1 to the variable checktype, rather than testing for equality:

function test(name,type) {
  if (type == 1) {
    document.myform.name.value = name;
  }
}
richsage
@Yanksy yes, unless the value of type determines what you do next... :-)
richsage
+1  A: 

Javascript uses == for equality checks.

Bobby
+1  A: 
function test(name,type) {
  if (type === "1") {
    document.myform.name.value = name;
  }
}

No need to use an additional variable inside the function for storing the value. Also use ===' instead of==` if you know the type of the variable.

See Strict equal

Returns true if the operands are strictly equal (see above) with no type conversion.

rahul
thanks for the extra tip.
George
A: 
function test(name,type) {
  if (type==1) {
    document.myform.name.value = name;
  }
}
Sani Huttunen
+1  A: 

You need to use a comparison operator instead of an assignment operator:

function test(name, type) {
  if (type == 1) {
    document.myform.name.value = name;
  }
}

If you’re using an assignment operator, the whole expression evaluates to the assigned value. That means type = 1 evaluates to 1 that is equal true and the branching condition is always fulfilled.

Gumbo
thanks for the additional explanation.
George
+1  A: 

To avoid this type errors try to do this..

function test(name,type) {
  if (1 == type) {
    document.myform.name.value = name;
  }
}

In this case, if you type by mistake, 1=type, then you get an error and you locate it right way.

Aristos
Interesting tip, thanks.
George
Very old trick, comming from the C days, how ever there is a book called Writing Solid Code, that have a lot like that. Personally I used it all the time, when I write in C/C++ - (in C# it no needed, they not let you make this mistake)
Aristos