I'm using the following function to iterate through fields in a form.
However, I need to make sure it works both in IE and FireFox (and in other browsers)
I have succesfully used:
var elements = document.myForm.elements;
var length = elements.length;
for(var loop = 0; loop < length; loop++)
if(elements.item(loop).nam
e=="test")
alert('Test found');
However, it takes very very long time if there are many many fields in the form. I've identified that elements.item() is to blame
Now, I've changed it to
var elements = document.myForm.elements;
var length = elements.length;
for(var loop = 0; loop < length; loop++)
if(elements[loop].name=="t
est") alert('Test found');
This works much faster, but I've understood that it is not really the proper way to do things, as the use of elements[] implicitly uses the "all" collection that only works in Internet Explorer?
Or is this "only illegal" when doing it this way instead (I haven't really tried on FireFox yet):
var length = document.myForm.elements.l
ength;
for(var loop = 0; loop < length; loop++)
if(document.myForm.element
s[loop].na
me=="test"
) alert('Test found');
So, the question in:
which is the proper (compatible) way of iterating through fields in a form. And still not pay the performance penalty that item() seems suffer from.
Another way of doing it, which makes me pussled, is the following:
var elements = document.myForm.elements;
for(var value in elements)
if(value=="test") alert('Test found');
It works, but it iterates through a lot more than just the fields!
Apart from the field names themselves, values like "language, scrollHeight, isTextEdit, currentStyle" etc etc is looped through.
The "length" attribute of elements is however the same, such that the actual content of elements (seen by "for value in elements") is larger than the "length" attribute.
Why is this?
Start Free Trial