javascripthtmlhtml-selectselectedvalueselectedindex

value of select elements with "e.value" vs "e.options[e.selectedIndex].value"


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


Solution

  • 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:

    So I think it's safe to use.