Forum Moderators: open

Message Too Old, No Replies

Looping through all the elements of a form

Something wrong with my for loop

         

Greven

12:22 am on Mar 24, 2005 (gmt 0)

10+ Year Member



I'm trying to loop through all the elements of a decent size form. I understand that some elements will have sub elements(like options), but I'm just trying to go through the top ones. This is the code that I am using:

function runChange(f)
{
var elem = f.elements;
var flength = elem.length;
var i = 0;

document.write("flength: ");
document.write(flength);

for (i=0; i <= flength; i++)
{
document.write("<br>"+i+") ");

if ( elem[i] )
{
document.write("- ");

if (elem[i].type == "text")
{
document.write("Type["+i+"]: Text");
}
else if (elem[i].type == "checkbox")
{
document.write("Type["+i+"]: Checkbox");
}
else if (elem[i].type == "radio")
{
document.write("Type["+i+"]: radio");
}
else if (elem[i].type == "reset")
{
document.write("Type["+i+"]: radio");
}
else if (elem[i].type == "button")
{
document.write("Type["+i+"]: radio");
}
}
}
}

I have no idea what could be wrong with it, but this is the output:

flength: 49
0)
1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
13)
14)
15)
16)
17)
18)
19)
20)
21)
22)
23)
24)
25)
26)
27)
28)
29)
30)
31)
32)
33)
34)
35)
36)
37)
38)
39)
40)
41)
42)
43)
44)
45)
46)
47)
48)
49)

So its clearly looping, but it looks like everything single one of the elements doesn't exist? How could this be? Also, if I change it to this:


document.write("flength: ");
document.write(flength);
flength = elem.length;
document.write("<br>flength: ");
document.write(flength);

I get these results:

flength: 49
flength: 0
0)

Data corruption? I have no idea whats going wrong here. Any help would be greatly appreciated.

Greven

12:27 am on Mar 24, 2005 (gmt 0)

10+ Year Member



I guess I should specify that I'm calling this function in a way such as this:

<form name="bundform" action="get">
Tax Rate:<input type="radio" name="taxrate" value="7" onClick=runChange(this.form)>7%

Greven

6:14 am on Mar 24, 2005 (gmt 0)

10+ Year Member



Well, after a small test, I can see I should use <, not <= in the for loop, however I tried it on firefox and it works fine. However, the only place this is ever going to be used is in IE 6, so if anyone has some suggestions, I would be very appreciative.

SpaceFrog

8:39 am on Mar 24, 2005 (gmt 0)

10+ Year Member



try with
var elem = f.all;

kaled

8:40 am on Mar 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Instead of all the ifs and elses try something like

var t = elem[i].type;
document.write("Type[" + t + "]");

Kaled.

Greven

5:48 pm on Mar 24, 2005 (gmt 0)

10+ Year Member



I did get it to work with a little help, thanks for all the replies, looks like if I put a document.write anywhere but the last line of the function, it corrupts the data. This only happens in IE, and I have no idea why it would, but it does. Thanks again for the help.