value of select elements with “e.value” vs “e.opti

2020-03-04 07:07发布

问题:

Given the HTML:

<select id="mySelect">
    <option value="1">test1</option>
    <option value="2">test2</option>
    <option value="3">test3</option>
</select>

and the javascript:

var e = document.getElementById('mySelect');

To get the value of the select I can use e.value and e.options[e.selectedIndex].value.

I am aware that e.options[e.selectedIndex].value will give me the selected value (1,2 or 3) and e.options[e.selectedIndex].text would give me test1, test2, test3 depending on which is selected.

Is it ok to use just e.value? was this a problem in old browsers?
which is more correct: e.value vs e.options[e.selectedIndex].value?

jsFiddle

回答1:

The HTMLSelectElement interface includes the value attribute at least since Document Object Model (DOM) Level 1 Specification, from 1998.

However, like it is explained in this w3c mailing list, the problem was that HTML4.01 spec was vague:

It's true that HTML4.01 doesn't explicitly specify a value attribute for SELECT, but it does seem to be implied:

  • 'Menu' is a control type. (HTML4.01 17.2.1)

  • "Each control has both an initial value and a current value, both of which are character strings" (HTML4.01 17.2)

  • And SELECT may have an onchange attribute which implies a value. (HTML4.01 17.6)

But there's no mention of what the value represents, nor of what the initial or default values might be.

However, checking in IE5 and Mozilla, the value of SELECT does indeed return a string corresponding to the value of the currently selected OPTION.

(...) Probably wouldn't be a problem if HTML4.01 had been more explicit.

This was fixed in following definitions.

You can see it defined here:

  • HTMLSelectElement's value in DOM Level 1, W3C Recommendation, 01 October 1998

    The current form control value.

  • HTMLSelectElement's value in DOM Level 2, W3C Recommendation, 09 January 2003

    The current form control value (i.e. the value of the currently selected option), if multiple options are selected this is the value of the first selected option.

  • HTMLSelectElement's value in HTML5, W3C Candidate Recommendation

    The value IDL attribute, on getting, must return the value of the first option element in the list of options in tree order that has its selectedness set to true, if any. If there isn't one, then it must return the empty string.

So I think it's safe to use.



回答2:

Some old (~2005) threads from the comp.lang.javascript newsgroup, as well as their FAQ [1], mention that .value access was not supported in Netscape Navigator 4 (i.e. pre-2000), and some other mobile and desktop browsers that were considered "old" even at that time.

Conclusion (backed by @Oriol's DOM spec excerpts): It's totally safe to use today.