The value of select items with "e.value" versus "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 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 know it e.options[e.selectedIndex].value
will give me the selected value (1,2 or 3) and e.options[e.selectedIndex].text
will give me test1, test2, test3 depending on the selected one.
Can I only use e.value
? is this a problem in older browsers?
which is more correct: e.value
vs e.options[e.selectedIndex].value
?
source to share
The interface has HTMLSelectElement
included the attribute value
since at least the Document Object Model (DOM) level specification since 1998.
However, as described on this w3c mailing list , the problem was that the HTML4.01 spec was undefined:
It is true that HTML4.01 does not explicitly specify the value attribute for the SELECT, but this seems to be implied:
"Menu" is a type of control. ( 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 it
SELECT
can have an attributeonchange
that implies a value. ( HTML4.01 17.6 )But there is no mention of what the value represents, or what initial or default values might be.
However, checking IE5 and Mozilla, the value
SELECT
does return the string corresponding to the currently selected valueOPTION
.(...) This is probably not a problem if HTML4.01 was more explicit.
This has been corrected in the following definitions.
You can see how it is defined here:
-
HTMLSelectElement
value
in DOM Level 1 , W3C Recommendation, 01 October 1998The current value of the shape control.
-
HTMLSelectElement
value
in DOM Level 2 , W3C Recommendation, January 09, 2003.The current value of the shape control (i.e. the value of the currently selected parameter), if multiple options are selected, this is the value for the first option selected.
-
HTMLSelectElement
value
in HTML5, W3C Candidate RecommendationThe
value
IDL attribute on getting must return value first of theOPTION
item in the options list in the tree order , which has selectedness set to true, if any. If it's not there, then it should return an empty string.
So I believe it is safe to use it.
source to share
Some older (~ 2005) newsgroup threads comp.lang.javascript
, as well as their FAQ [1] , point out that .value
access was not supported in Netscape Navigator 4 (ie 2000) and some other mobile and desktop browsers that were considered "old "even at that time.
Conclusion (backed up by excerpts from @Oriol DOM spec): It's completely safe to use today.
source to share