0

Here on page load i am trying to store the values from form to variables. Later i would like to use those variables (if and only if i have data in that) to other purpose.

This is how i approached ( on page load )

render : function() {
 frm = document.Form;

 if (frm.Name1.value){
                value1 = frm.Name1.value;
        }
 if (frm.Name2.value){
            value2 = frm.Name2.value;
        }
if (frm.Name3.value){
            value3 = frm.Name3.value;
        } 

}

Based on certain condition / selection i will call this function to assign initially loaded values

function add_values ( ) {
      if (value1.length){
            frm.Name1.value = value1;
        }
       if (value2.length){
            frm.Name2.value = value2;
        }
        if (value3.length){
            frm.Name3.value = value3;
        }
}

Error: ( in firebug )

value3 is not defined
[Break On This Error] if (value3.length){ 

What did i try ?

if (undefined != value3)
Mad-D
  • 4,479
  • 18
  • 52
  • 93
  • possible duplicate of [How can I check whether a variable is defined in JavaScript?](http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript) – shadyabhi Feb 10 '12 at 23:02

4 Answers4

2

try

if(typeof value3 != "undefined")

more on typeof

Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40
Kai Qing
  • 18,793
  • 5
  • 39
  • 57
  • typeof is exactly what it sounds like. it returns the type of the variable in string format. see here: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof so in this case if typeof returns "undefined" then you know it was not previously set. – Kai Qing Feb 10 '12 at 23:16
1

You can use:

typeof value3 != 'undefined'
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
0

To check if something is undefined:

if (typeof value3 === 'undefined') {
    // It's undefined!
}
Rophuine
  • 724
  • 3
  • 8
0

Just check whether the variable's type is undefined:

if (typeof value3 !== 'undefined') {
  // value3 is defined
}

If you want, you can make a PHP-like function for that:

function isset(variable) {
  return typeof variable !== 'undefined';
}

if (isset(value3)) {
  // value3 is defined
}
Blender
  • 289,723
  • 53
  • 439
  • 496