本文翻譯自:jQuery Get Selected Option From Dropdown
Usually I use $("#id").val()
to return the value of the selected option, but this time it doesn't work. 通常,我使用$("#id").val()
返回所選選項的值,但是這次不起作用。 The selected tag has the id aioConceptName
所選標籤的ID爲aioConceptName
html code HTML代碼
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
#1樓
參考:https://stackoom.com/question/iiuv/jQuery從下拉列表中獲取選定的選項
#2樓
For dropdown options you probably want something like this: 對於下拉選項,您可能想要這樣的東西:
var conceptName = $('#aioConceptName').find(":selected").text();
The reason val()
doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the :selected
property to the selected option which is a child of the dropdown. val()
不能解決問題的原因是,單擊選項不會更改下拉菜單的值,它只是將:selected
屬性添加到作爲下拉菜單的子級的selected選項中。
#3樓
I stumbled across this question and developed a more concise version of Elliot BOnneville's answer: 我偶然發現了這個問題,並開發了一個更爲簡潔的Elliot BOnneville答案:
var conceptName = $('#aioConceptName :selected').text();
or generically: 或一般而言:
$('#id :pseudoclass')
This saves you an extra jQuery call, selects everything in one shot, and is more clear (my opinion). 這樣可以節省您額外的jQuery調用,一次即可選擇所有內容,而且更加清晰(我認爲)。
#4樓
Try this for value... 嘗試此物有所值...
$("select#id_of_select_element option").filter(":selected").val();
or this for text... 或這個文本...
$("select#id_of_select_element option").filter(":selected").text();
#5樓
<select id="form-s" multiple="multiple">
<option selected>city1</option>
<option selected value="c2">city2</option>
<option value="c3">city3</option>
</select>
<select id="aioConceptName">
<option value="s1" selected >choose io</option>
<option value="s2">roma </option>
<option value="s3">totti</option>
</select>
<select id="test">
<option value="s4">paloma</option>
<option value="s5" selected >foo</option>
<option value="s6">bar</option>
</select>
<script>
$('select').change(function() {
var a=$(':selected').text(); // "city1city2choose iofoo"
var b=$(':selected').val(); // "city1" - selects just first query !
//but..
var c=$(':selected').map(function(){ // ["city1","city2","choose io","foo"]
return $(this).text();
});
var d=$(':selected').map(function(){ // ["city1","c2","s1","s5"]
return $(this).val();
});
console.log(a,b,c,d);
});
</script>
#6樓
Have you considered using plain old javascript? 您是否考慮過使用普通的舊JavaScript?
var box = document.getElementById('aioConceptName');
conceptName = box.options[box.selectedIndex].text;
See also Getting an option text/value with JavaScript 另請參閱使用JavaScript獲取選項文本/值