Reputation: 11
Hi I have sevral selects on my page with the name viewer[].
In javascript I wish to iterate through this array and get each ones selected index.
var welements = document.getElementsByName('viewer[]')[0];
for ( var i in welements )
{
alert(i.selectedIndex);
}
I have above but its clearly wrong. I beleive the first line is correct - document.getElementsByName returns an array so I just want the first (and only) result which is the viewer[] html array
Advice appreciated, thanks!
Upvotes: 1
Views: 10419
Reputation: 22087
To iterate over an Array you shouldn't use the "for (i in array)" form. That is bound to return items which are not the numeric indices of the array... other names like "length" and "items".
Use this instead:
var welements = document.getElementsByName('viewer[]');
for (var i = 0; i < welements.length; i++)
{
alert(welements[i].selectedIndex);
}
Note as S.Mark said you don't want the [0] on the first line, as that is grabbing only the first item. Or maybe you do want it... you're unclear on that. You said you have multiple things named "viewer[]", yet you also imply you want only the first one. If that is really true, then you don't need the loop at all! welements.selectedIndex would already give you that value for the first "viewer[]" item.
Upvotes: 1
Reputation: 944205
getElementsByName requires a NodeList, not an Array. NodeLists are very much like Arrays, but there are differences.
Either way, you shouldn't iterate over them using for (foo in bar)
— that gets all the properties (including foo.length
), not just the values you care about.
Use:
var welements = document.getElementsByName('viewer[]'); // Removed [0], that gets the **1st** node, not the NodeList.
for (var i = 0, j = welements.length; i < j; i++) {
var an_element = welements[i];
alert(an_element.selectedIndex);
}
Upvotes: 7
Reputation: 146
Using "for each"(for in) in javascript returns all attributes inside the array that includes arrays prototypes attributes. So its not advised, better if you iterate like
for(var i=0; i < welements.length; i++){
alert(welements[i].selectedIndex);
Upvotes: 3
Reputation: 123889
3 check points
wlements[i]
instead of i
[0]
will not needed on first lineviewer[]
? i think viewer
only.If me, I will do like this
var welements = document.getElementsByName('viewer');
for ( var i in welements ){
alert(welements[i].selectedIndex);
}
If you only want first one, for loop is not needed
var welements = document.getElementsByName('viewer')[0];
alert(welements.selectedIndex);
Upvotes: 0