Link to home
Start Free TrialLog in
Avatar of snobunny
snobunny

asked on

Checking to see if a field exists in Javascript

In Javascript, is there a way to check if a field exists before referring to it?
 
The reason I ask is whenever my document loads I execute the following passthrough Javascript.

<Script Language="Javascript">
{if (document.forms[0].customerName.value =="Error") {alert("The customer number is invalid");document.forms[0].customerNumber.focus()}}
</Script>

This works great as long as the document is in edit mode, however, if I try to open the document in read mode I get the error "document.forms[0].customerNumber is not an object".  Because the document is in read mode it doesn't see the customerNumber field.  How can I skip this code if the document is opened in read mode?  I can't use hide-when's because if I do the HTML style is taken away from my passthrough HTML.
Avatar of ghassan99
ghassan99

What version of Notes r u using?
You can use hide/when without losing the passthrough HTML property, and your script will generate no errors.

-Gus
Hi

You can test whether an object is available or not by testing for undefined value, here is the sample of it:
[<Body onLoad="test()">]

<SCRIPT Language="Javascript">
function test(){
      if (document.forms[0].customerName==undefined)
      alert("True");
}
</SCRIPT>




Good Luck
~Hemanth
Avatar of snobunny

ASKER

Your example works in Netscape 4.08 (Actually my code always worked in Netscape) but still does not work in IE 4.0

I now get the following error message:  

Error: 'undefined' is undefined
ASKER CERTIFIED SOLUTION
Avatar of ghassan99
ghassan99

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
Hi All

I have tested my code on NS and found to work, but I curse myself for not testing on the IE, anyway as gus mentioned typeof is preferable and works perfectly on both browsers.

~Hemanth
Your solution worked in NS but did not work on IE.  The solution that Gus provided worked on both.  I will award the points to Gus.  Thanks for answering my question.
Thanks for your answer, Gus.  I have tried it out and it works great!
No problem...:)

-Gus