Note: this question has nothing to do with Knockout.js, but it's about the selectedOptions
attribute of <select>
elements instead. This is the reference:
http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#dom-select-selectedoptions
I think it's a nice feature for Javascript developers. The support is quite limited, but it's growing anyway. Chrome, Opera and Safari should already support it.
The problem is that I can't figure out how it works. The behaviour should be quite straightforward, yielding a live collection of the selected options, but it turns out to be not the case. You'd imagine that selectedOptions
changes everytime the user selects an option, right? Wrong. I've prepared a test case:
http://jsfiddle.net/f39cC/5/
In this example, Opera 11.64 always returns the first value selected, no matter what you do after, while Chrome 21 dev and 19 stable have an odd behaviour. Do the following steps:
- Select 'One'. In both output and console you get "One", as expected.
- Select 'Two' too, using Ctrl. In console you get "One,Two", in output it's still "One".
- Select 'Three' too. In console it's "One,Two,Three", in output it's "One,Two".
- Now select 'Two' only. In console you get "Two", in output "Two,," (notice the two commas).
However, if you comment out the console.log
line, you always get the correct output. You can get the expected behaviour in both console and output if you swap the two instructions, or if you store the value in a separated string, as in this:
http://jsfiddle.net/f39cC/2/
So, am I missing something about selectedOptions
? Is it too soon to rely on this property, that probably has a buggy implementation? Is console.log
creating the issue in Chrome? Is there something I don't know about HTMLCollection
s?
I don't have Safari installed, can someone check its behaviour?
UPDATE 18/2/2013: I don't know when things have changed, but both Chrome 24.0.1312.57 and Opera 12.14 seems to work fine now. Firefox 18.0.2 and Internet Explorer 10 still have to implement the property.
UPDATE 17/9/2013: Firefox 24 and IE 11 preview still have to support the property. This is an easy workaround for Firefox and IE8-11:
Object.defineProperty(HTMLSelectElement.prototype, "selectedOptions", {
get: (function() {
try {
document.querySelector(":checked");
return function() {
return this.querySelectorAll(":checked");
};
} catch (e) {
return function() {
if (!this.multiple) {
return this.selectedIndex >= 0
? [this.options[this.selectedIndex]] : [];
}
for (var i = 0, a = []; i < this.options.length; i++)
if (this.options[i].selected) a.push(this.options[i]);
return a;
};
}
})()
});
For IE8 it returns just an Array
and not a NodeList
, though.
UPDATE 28/5/2014: It looks like Firefox started implementing selectedOptions
since r25.
See Question&Answers more detail:
os