-1

I have an old application that didnt use jquery.

so is an HTML select object.

This code gives an error, that value is not set in the second line of:

for (var i in so.options){
        if(so.options[i].value=='X') {
            // do something
        }
}

It works in Firefox though. How can I catch this without jquery?

rubo77
  • 19,527
  • 31
  • 134
  • 226
  • What type of object is `so.options`? – Chris Walsh Feb 25 '15 at 12:09
  • 2
    Read this [SO question](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) and this [SO question](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript?rq=1) – Max Brodin Feb 25 '15 at 12:09

2 Answers2

0

Thanks to @Mathieu Amiot's comment:

You can also be clever. for(var i = 0, l = myArray.length; i < l; ++i) ... is the fastest and best you can get with forward iteration.

So my solution for IE and FF:

for(var i = 0, l = so.options.length; i < l; ++i){
    if(so.options[i].value=='X') {
        // do something
    }
}
Community
  • 1
  • 1
rubo77
  • 19,527
  • 31
  • 134
  • 226
0

This is probably because the first property of so.options is the .length property, which is numeric and not an object.

To iterate an HTMLOptionsCollection, you need to do it like this:

for (var i = 0; i < so.options.length; ++i) {
    if (so.options.item(i).value == 'X') {
    }
}

Most browsers will probably provide a convenience accessor, though, so so.options[i].value should work as well.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309