views:

267

answers:

2

Hi, I would like to select certain elements in form by their name, so I suppose using getElementsByName(name). Then I would like to add a value to these elements. How do I do this loop?

boxesEL = document.getElementsByName(boxesName);

for(var x=0;x<=boxesEL.length;x++){
    boxesEL[x].value = "some value";
}

I'm getting an error boxesEL[x] is undefined.

+5  A: 

Take out the "=" sign in the comparison in the for loop. You're looping one too many times. Length gives you the number of elements - the maximum index of the collection will be one less, because it's zero based.

for(var x=0; x < boxesEL.length; x++)   // comparison should be "<" not "<="
{
    boxesEL[x].value = "some value";
}
womp
thanks, that was quick.
perfectDay
A: 

Welcome to arrays :)

Computers start counting at 0 for array indexes, however the length will be the human countable number. An example:

myArray = ['first element', 'second element'];
myArray.length; // returns 2, since there are 2 elements in the array
myArray[0]; // returns 'first element'
myArray[1]; // returns 'second element'
myArray[2]; // returns undefined, since it hasn't been set.
myArray[myArray.length]; // this is the same as myArray[2] - hence returning undefined

In for loops using arrays, you need to check for one less than the size of the array, so as womp mentioned your code should be:

for(var x=0; x < boxesEL.length; x++)   // comparison should be "<" not "<="
{
    boxesEL[x].value = "some value";
}
slightlymore