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

こ雲淡風輕ζ 提交于 2019-11-30 22:52:41

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!