Strawberry
Strawberry

Reputation: 67888

getElementById(array[x])?

I'm trying to put an array in to getElementById for a loop purpose. It seems to be not working, how can I do this?

Edit: Sorry folks It says undefined.

    var lol=new Array( "test", "test2" );

var x = 0;
while( x == 4 ) {
    number = parseInt(document.getElementById(lol[x]).value);
    x++;
}

And i have inputs id named test and test2.

Upvotes: 0

Views: 29901

Answers (3)

Aaron
Aaron

Reputation: 7098

Your while loop only works if x==4. Change this to:

while(x < lol.length)

To loop through all the elements in the array. Better yet, this will condense your loop:

var lol=new Array( "test", "test2" );
for( var x = 0; x < lol.length; x++ ) {
    number = parseInt(document.getElementById(lol[x]).value);
}

Upvotes: 8

Anonymous
Anonymous

Reputation: 50349

You say you have number = parseInt(document.getElementById("lol[x]").value);

  1. "lol[x]" is a string with that literal value, not the value that lol holds at index x. Use getElementById(lol[x])

  2. parseInt may do unexpected things when you don't pass a radix. Use something like parseInt(document.getElementById(lol[x]).value, 10)

Finally, you aren't checking whether the element exists. Do something like:

var element = document.getElementById(lol[x]);
if (element) {
  number = parseInt(element.value, 10);
} else {
  // handle error or throw exception
}

Upvotes: 0

cjstehno
cjstehno

Reputation: 13984

Try taking your array out of the quotes...

document.getElementById(lol[x]).value

The quotes turn it into a static string "lol[x]", when you want the value of the lol array at x index.

This replaces my earlier, less informed answer.

Hope this helps

Upvotes: 1

Related Questions