Javascript jquery获取所有下拉值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3923858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:40:22  来源:igfitidea点击:

jquery getting all dropdown values

javascriptjquery

提问by bba

I have dropdown <select>with id my_dropdown. I allow multi-select. I know how to pull the selected value(s) using jquery:

我有下拉菜单<select>id my_dropdown。我允许多选。我知道如何使用 jquery 提取选定的值:

var values = $('#my_dropdown').val();

This will return an array of values if I select multiple. I also need to get all the values in the dropdown regardless of what is selected. How can I use jquery similarly to get all the values in the dropdown given that id?

如果我选择多个,这将返回一个值数组。无论选择什么,我还需要获取下拉列表中的所有值。如何使用 jquery 类似地获取给定 id 的下拉列表中的所有值?

回答by VoteyDisciple

How about something like:

怎么样:

var values = [];
$('#my_dropdown option').each(function() { 
    values.push( $(this).attr('value') );
});

回答by jAndy

Looks like:

好像:

var values = $('#my_dropdown').children('option').map(function(i, e){
    return e.value || e.innerText;
}).get();

See this in action: http://www.jsfiddle.net/YjC6y/16/

看看这个:http: //www.jsfiddle.net/YjC6y/16/

Reference: .map()

参考:.map()

回答by user113716

Example:http://jsfiddle.net/FadHu/

示例:http : //jsfiddle.net/FadHu/

var opts = $('#my_dropdown')[0].options;

var array = $.map(opts, function( elem ) {
    return (elem.value || elem.text);
});

The <select>element has a list of the options in its optionsproperty. Then use $.map(), which returns an array, to get either the option's valueor textproperty.

<select>元素在其options属性中有一个选项列表。然后使用$.map()返回一个数组的 来获取选项valuetext属性。

(Note the $.map()behaves a little differently from $(element).map(). Can be a little tricky.)

(注意 的$.map()行为与 略有不同$(element).map()。可能有点棘手。)