Click to See Complete Forum and Search --> : Moving through controls


TenKracer
11-17-2003, 02:15 PM
Hi all,
I can't seem to get this to work.

I have an unknown number of textboxes on my form. They will be called person(i) so if I have 3 textboxes I will have person1, person2, and person3. I want to be able to create a for loop that will loop through each one of these controls...

Something like

For i = 1 to 3
{
document.myform.personi.value
}

How do I increment the control name correctly?

Cheers,
Mike

TheBearMay
11-17-2003, 02:33 PM
Try something like this:

for (i=0; i<NumElem; i++){
BoxName='Person'+i;
BoxValue=document.myform.eval(BoxName).value;
}

TenKracer
11-17-2003, 02:37 PM
Cool deal,
Thanks a lot. This will save me a lot of time and make my code look a little bit nicer.

fredmv
11-17-2003, 02:40 PM
You just about never need to use eval; the only time I've ever seen to prove useful is to avoid scoping issues, but that isn't the case in this instance. You need to recall that the form object has an elements array in which it's child elements can be accessed though. It could be as simple as this:

for(i=0 i<theForm.elements.length; i++) theForm.elements['element' + i ].value = 'This is element ' + i + '.';

This is where theForm is a reference to the form object you want to access. The main reason you would want to avoid using eval is becuase it uses more resources than just about any other JavaScript method. It just doesn't make sense to waste precious resources when you have other (less resource heavy) methods available to you. The more calls you make to eval, the longer it will take for your script to execute, and that really isn't what you want.

Good luck.

TenKracer
11-17-2003, 02:43 PM
OK, that makes sense... But if I am using asp to create these controls how can I tell what the elements # is?