如何通过JavaScript获取<select>中当前选择的<option>?

Pau*_*ite 55 html javascript html-select

如何通过JavaScript 获取当前选定<option><select>元素?

Pat*_*Pat 95

这将为您做到:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )
Run Code Online (Sandbox Code Playgroud)

  • 如果你用它来访问选项的值,你也可以使用`yourSelect.value`.非常古老,古老的浏览器可能不支持它,但IE6和每个现代浏览器都支持它. (10认同)

Amb*_*ber 19

.selectedIndex所述的select对象具有的索引; 你可以用它来索引.options数组.

  • 这是最优雅、最直接的方法 (2认同)

小智 5

var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );
Run Code Online (Sandbox Code Playgroud)


Fin*_*sse 5

使用该selectedOptions属性:

var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);
Run Code Online (Sandbox Code Playgroud)

适用于除 Internet Explorer 之外的所有浏览器。

  • “它适用于除 Internet Explorer 之外的所有浏览器。” 一旦每个人都停止使用 Internet Explorer,我们就万事大吉了![这里可能有polyfill](https://gist.github.com/brettz9/4212217)。 (3认同)