2010-07-21 23 views
43

如何通過JavaScript將選爲選擇<option><select>元素?如何通過JavaScript在<select>中獲取當前選中的<option>?

+1

可能的重複:[如何使用JavaScript獲取dropdownlist的選定值?](http://stackoverflow.com/questions/1085801/how-to-get-the-selected-value-of-dropdownlist-using- javascript) – 2013-05-26 07:33:18

+1

@AndersonGreen:那不是*完全相同的問題。它實際上是要求如何獲得選擇'

回答

78

這會爲你做它:

var yourSelect = document.getElementById("your-select-id"); 
alert(yourSelect.options[ yourSelect.selectedIndex ].value) 
+9

如果您使用它來訪問該選項的值,那麼您可以使用'yourSelect.value'。很古老的,古老的瀏覽器可能不支持它,但IE6和每個現代瀏覽器都支持。 – 2010-07-21 16:52:03

+0

@Andy E:哦,有一個想法 - 這確實是我正在做的,而且你的代碼更容易閱讀。 – 2010-07-21 17:02:54

+0

@Andy E:啊,關於這個方法的一個警告 - 它不會在IE中返回'

17

select對象的.selectedIndex有一個索引;你可以用它來索引.options數組。

+0

這絕對比頂級答案更有語義意義! – 2015-06-07 21:34:50

+0

這是最優雅和直接的方法 – Rice 2016-10-10 18:06:50

2
var payeeCountry = document.getElementById("payeeCountry"); 
alert(payeeCountry.options[ yourSelect.selectedIndex ].value); 
+0

您的答案因其長度和內容而被標記爲「低質量」。我可以建議你對這個問題做出評論嗎? – 2016-11-21 15:45:51

1

使用selectedOptions屬性:

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

works除了Internet Explorer中的所有瀏覽器。

+0

「它適用於除Internet Explorer之外的所有瀏覽器。」只要所有人都停止使用Internet Explorer,我們就是黃金版! [可能在這裏填充](https://gist.github.com/brettz9/4212217)。 – 2018-01-31 08:42:29

相關問題