Search code examples
javascripthtmlqunitselectedindex

Select Option - cannot get selected option


I think there is something wrong with my Select/Options tag... I cannot access the selected option.

Here's the HTML part:

<select id="filter">
    <option value="value1" selected="selected" data-path="property1">option1</option>
    <option value="value2" data-path="property2">option2</option>
</select>

I tried this way:

var property_filter = document.getElementById('filter');

And while debugging, on the console, this is what I tried:

input:  property_filter.options
output:  [<option value=​"value1" selected=​"selected" data-path=​"property1">​option1</option>​,<option value=​"value2" data-path=​"property2">​option2​</option>​]

So it's grabbing the right select tag... But something is still wrong:

input:  property_filter.selectedIndex
output:  -1

Similary, when I used JQuery selector to find this, I'm not getting what I want.

input:  $('#filter').find('option')
output:  [<option value=​"value1" selected=​"selected" data-path=​"property1">​option1​</option>​, <option value=​"value2" data-path=​"property2">​option2​</option>​]

input:  $('#filter').find('option:selected')
output:  []

I must be doing something wrong... It's such a simple task, too. I also tried using 'selected', not 'selected="selected"' but I got the same result.

I'm using Chrome on OS 10.6.8 by the way, and under context of Backbone View & QUnit test (but it shouldn't matter, right?). Also, this code works outside of QUnit.


Solution

  • Ah... Sorry. I found out why things were not working. And like Peter Wilkinson said, it was a bug that I introduced.

    Before I try to get the index, I set the index to 2, (noob mistake!!) which set the index to out of bound index. That's why I kept getting -1 as index.

    There was nothing wrong with JQuery or selectedIndex or any of the methods that I tried + I should have debugged further up.