Click to See Complete Forum and Search --> : ? regarding traversing the elements of a form


tbroas
07-20-2006, 12:46 PM
I have a question about traversing (or indexing) the elements of a form. From searching around, I know that I can access the elements of a form by using something like:

document.forms[0].elements[number]

I have a form where some of the elements are created dynamically, so I won't always know exactly how many elements the form will have. Is there something that I can use to determine the number of elements that exist? I'd like to use a for loop or something:

for (var i=0; i < document.form[0].element.size? < i++)
{
.
.
.
}


I put in document.form[0].element.size as an example, is there something in javascript like this that tells me the number of elements in the form? Thanks in advance for the advice

PineSolPirate
07-20-2006, 01:13 PM
I think you want ".length" that gives the number of indicies in an array.
<script language="JavaScript">
function test ()
{
var theForm = document.getElementById('theForm');
var theFields = theForm.elements;
alert("There are "+theFields.length+" fields.");
}
</script>
</head>
<body>

<form id="theForm">
<input type="text" name="txtRef1Name" value="John" />
<input type="text" name="txtRef1Name" value="Q" />
<input type="text" name="txtRef1Name" value="Smith" />
<input type="button" onclick="test()" value="test" />
</form>* It's also counting the test button, since that is an element in the form.

tbroas
07-20-2006, 02:02 PM
Thanks for the code. Is there a way to get it to ignore buttons?

PineSolPirate
07-20-2006, 02:21 PM
Well, if you know how many buttons there are you could just subtract that number. Otherwise you can use something like this:
<script language="JavaScript">
function test ()
{
var theForm = document.getElementById('theForm');
var theFields = theForm.elements;
var count = 0;
for (var i=0; i<theFields.length; i++)
{
if("button" != theFields[i].getAttribute("type") && "submit" != theFields[i].getAttribute("type"))
{
count++;
}
}
alert("There are "+count+" fields that aren't buttons.");
}
</script>
</head>
<body>

<form id="theForm">
<input type="text" name="txtRef1Name" value="John" />
<input type="text" name="txtRef1Name" value="Q" />
<input type="text" name="txtRef1Name" value="Smith" />
<input type="button" onclick="test()" value="test" />
</form>