jQuery从下拉列表中获取选定的选项

本文翻译自: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获取选项文本/值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章