Link to home
Start Free TrialLog in
Avatar of faster
faster

asked on

check whether an object exists

In javascript, how do I know whether a particular object exists or not?

For example, suppose f is a form,

var field = eval("f." + "address");
field.value = "USA";

This code is fine if there is a field named "address" in the form, but if such
a field does not exist (since the javascript function will be a common one)
how can I tell that field is undefined and therefore skip the assignment
which will cause an error?

Must work for IE and Netscape.

ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of faster
faster

ASKER

The last option is actually not what I want, because it requires an iteration of all fields of the form, which is expensive.  The 1st is good for me.
Thanks,

But how many fields do you have? It would take at least 50+ fields to make a difference as far as I have seen.

Michel
I was just having this problem myself, and I thought this may help:

//JavaScript 1.3 added the if(x==undefined) capability, but previous versions require a workaround
function isDefined(o) {
      varToStr=eval("' "+o+"'");
      if (varToStr==" undefined") {
            return false;
      } else {
            return true;
      }
}
And also added === that will test for null

Michel