"document.formName" undefined?

I have an ASP.NET site running locally on my XP system using IIS Express. There is a live version of a site running on a Windows server.

On web pages, often Javascript will refer to the form on the page using the document.formName style, where formName is the name of the form. As far as I know, this is a cross-browser method, along with document.forms.formName and document.forms[0] , etc.

On my local development site, the link is document.frm1 (I know the wrong naming practice); it is undefined. On the other hand, document.forms.frm1 working fine. Oddly enough, this does not happen on the server, although both pages are identical as you progress through the code. I double checked with Firebug, both in IE8 and Firefox 6.

Another weird part: checking with Firebug, document.frm1 is undefined, but document.frmClose (another form) exists! BUT?!

Has anyone experienced this before?

+7
source share
4 answers

EDIT 1

I did some experimentation and found that the id property is used for document.forms , while the name property is apparently used for document.formName

http://jsfiddle.net/GVjsv/


Original answer

Make sure your javascript is not running before the DOM is ready. One way to help is to place your javascript at the bottom of the page or use the framework so that it wraps the code in the ready -type function:

jQuery: http://api.jquery.com/ready/

Mootools: http://mootools.net/docs/core/Utilities/DomReady

Vanilla javascript:

 window.onload = function() { // Code to be run. } 

The reason this is incompatible between servers may be because the local development server loads the page faster than the real-time server. Time works so that you usually don’t get the same error in both places - emphasis is added because if you tried enough time, you can probably reproduce the error in both places.

+12
source

To get the name attribute added to the form element, you need to add ...

 <system.web> <pages controlRenderingCompatibilityVersion="3.5" /> <!-- http://www.asp.net/whitepapers/aspnet4/breaking-changes --> </system.web> 

... in web.config

+6
source

I recommend not using the name attribute for JavaScript identification purposes. Instead, give the element an id and use

 document.getElementById("elementId"); 

eg.

 <form id="form1"></form> <script> var form = document.getElementById("form1"); </script> 
+3
source

The best solution for this:
Just add the name property to the form tag


If you use the code below

 <form id="form1"></form> <script> var form = document.form1; //getting undefined error here </script> 

What you need to do here:
add the "name" property in the form tag as shown below

 <form id="form1" name="form1"></form> <script> var form = document.form1; //Now it will work fine and provide the correct value </script> 
0
source

All Articles