views:

30

answers:

2

Hi!

I have a form validation routine in JS which cycles through elements of a the first form on the page. I read the size of the elements array like this:

maxi=document.forms[0].elements.length;

This works fine in IE returning 23. In FF it always returns 0 and no validation at all is performed.

Any suggestions?

Thanks!

+1  A: 

Move your javascript after the mark up or make sure that it runs after the document is loaded. Sounds like in FF the code is running before the form has been added to the DOM.

You might also consider using a javascript library, such as jQuery (I would recommend this), MooTools, Prototype, etc. to iron out a lot of the inevitable cross-browser issues you will have. Using jQuery, and the validation plugin, the validation code is very simple, using CSS classes to help with validation.

 <script type="text/javascript" src="jquery.js" />
 <script type="text/javascript">
      $(function() { // run on document load
           $('form').validate();  // use validation plugin to validate form
      });
 </script>


 <form ...>
     <input type="text" id="txt" name="txt" class="required" /> <!-- a required element -->
     <input type="text" id="num" name="num" class="required number" /> <!-- a required, numeric element -->
     ...
 </form>
tvanfosson
A: 

You should try some interactive javascript console to test issues like this - but, for this particular thing, you could use the "for ...in" form of for to iterate over the elements:

http://en.wikipedia.org/wiki/Foreach#JavaScript

Probably, however, it is the "elements" property which is non-standard there, so you will need to check the DOMs to get to a better way to retrieve the form widgets as objects.

And finally: beware of cleint side verification: it is often a burden to users and, if special care is not taken, it is to ease to have your forms stop working on a variety of browsers/platforms due to a verification which is mostly meaningless anyway (since you must verify the lenght of data entered server side in either case)

jsbueno