Javascript 如何在下拉列表中获得多个选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13857049/
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-24 14:57:20  来源:igfitidea点击:

How can I get a multiple selected values in dropdown

javascriptjqueryhtml

提问by Abhi

I am using drop down with multiple select name defined with select[]

我正在使用带有多个选择名称的下拉列表 select[]

How can I get selected values using jquery.

如何使用 jquery 获取选定的值。

采纳答案by Rory McCrossan

The same way as any form element - use val().

与任何表单元素相同的方式 - 使用val().

var selectedValues = $("#select").val();

With a multiple select you will see the value as a comma delimited string which can easily be posted for server-side processing or split into an array if required.

通过多选,您将看到以逗号分隔的字符串形式的值,可以轻松发布以供服务器端处理或根据需要拆分为数组。

Example fiddle

示例小提琴

回答by Narayan Subedi

If someone wants valueswith labels. Then here is the solution:

如果有人想要带有标签的。然后这里是解决方案:

var hexvalues = [];
var labelvalues = [];

$('#myMultiSelect :selected').each(function(i, selectedElement) {
 hexvalues[i] = $(selectedElement).val();
 labelvalues[i] = $(selectedElement).text();
});

回答by Murali Murugesan

Try

尝试

 var selectedItems= $('#ddlId option:selected');

selectedItems.each(function(obj,ind){
     $(obj).val() ;
} // or do with for (var i=0// normal js loop

回答by Adil

Try this,

尝试这个,

Live Demo

现场演示

$('#btn').click(function(){
    $('#select option:selected').each(function(){
        alert($(this).text());
    });
})?

回答by Aldry Wijaya

you should try this:

你应该试试这个:

$("select[name^='select[']:eq(0)").val();

remember, that eq(0) is indicated what is the index of your element with the same name.

请记住, eq(0) 表示同名元素的索引是什么。