Reputation: 561
I'm trying to create variabels on the fly in a for loop. error. What I'm trying to do is: get the values of 32 text fields and trying to store those values into a variable.
for (i = 1; i<=32;i++){
q[i] = document.getElementById('qty[i]').value;
}
But this yeilds:
Error: 'q' is undefined
Upvotes: 3
Views: 2799
Reputation: 53311
var q = [];
for (var i = 0; i < 32; i++){
q[i] = document.getElementById('qty[i]').value;
}
q
will contain all of your values. You should declare the array q
outside of your for loop, as that's the commonly accepted best practice. If you don't declare q
at all, it will be come an implied global variable, something that you probably want to avoid. If you declare q
inside your loop, it will get overridden each iteration, so you need to make sure you declare it outside.
Also, you'll note that I changed your for
loop from this:
for(i = 1; i <= 32; i++) {
To this:
for (var i = 0; i < 32; i++){
You're looping from 1 to 32; this is incorrect, as arrays in Javascript are 0-indexed; in other words, they start counting from zero. Since this is the case, your for
loops also need to start counting at zero, and end at 31. Also, you'll want to declare the var i
in your for loop; otherwise, it will become a global variable.
Now, if you really really didn't want to declare q
outside of your for loop, you could do what Kirian demonstrated; that is, use an if
statement to determine if q
has already been declared, and if not, declare it. That would look like this:
for (var i = 0; i < 32; i++){
if(!q) q = [];
q[i] = document.getElementById('qty[i]').value;
}
And another note, if qty
is an array in your code then you probably want this instead:
var q = [];
for (var i = 0; i < 32; i++){
q[i] = document.getElementById(qty[i]).value;
}
If instead qty
is part of a set of IDs that look like qty[1], qty[2], qty[3]...
, then you want this:
var q = [];
for (var i = 0; i < 32; i++){
q[i] = document.getElementById('qty[' + i + ']').value;
}
Upvotes: 4
Reputation: 189686
Have you tried:
var q = [];
for (var i = 0; i < 32; i++){
q.push(document.getElementById('qty[i]').value);
}
The syntax q.push(x)
appends x to the end of an array.
Upvotes: 2