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.
snobunnyAsked:
Who is Participating?
 
ghassan99Connect With a Mentor Commented:
I dont think its actually working in Netscape!  But probably netscape is more tolerant.  The proper way to test for a field is using the typeof operator, without that u r actually checking if the field has value or not.
Use it like this:

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

And I still think that hiding the text will not remove its passthru property.

-Gus
0
 
ghassan99Commented:
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
0
 
HemanthaKumarCommented:
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
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
snobunnyAuthor Commented:
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
0
 
HemanthaKumarCommented:
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
0
 
snobunnyAuthor Commented:
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.
0
 
snobunnyAuthor Commented:
Thanks for your answer, Gus.  I have tried it out and it works great!
0
 
ghassan99Commented:
No problem...:)

-Gus
0
All Courses

From novice to tech pro — start learning today.