jQuery 从表单中的所有选择元素中获取所有选择的选项元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12457891/
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
Get all selected options elements from all select elements in a form
提问by Dragan
Hi all and thanks for taking the time to answer my question.
大家好,感谢您花时间回答我的问题。
I have a form with 6 select elements with the class of "skillLevel". I need to get (preferably in an array] the values of each select element using jQuery.
我有一个包含 6 个选择元素的表单,类别为“skillLevel”。我需要使用 jQuery 获取(最好在数组中)每个 select 元素的值。
How can I do that?
我怎样才能做到这一点?
回答by undefined
You can use map
method:
您可以使用map
方法:
var arr = $('select.skillLevel').map(function(){
return this.value
}).get()
arr
is an array of values.
arr
是一个值数组。
回答by verisimilitude
var array = [];
$('.skillLevel option:selected').each(function() {
array[ $(this).val()] = $(this).text();
});
回答by rahul
Something like this will do that for you.
像这样的事情会为你做到这一点。
var val = new Array();
$("select.skillLevel").each(function(){
val.push(this.value);
});
回答by Usman
回答by Ravi
Hope this fiddle will help you : All selected options
希望这个小提琴能帮助你: 所有选定的选项
回答by Amedio
I think that you have to use $(".skillLevel")
to select all the elements you want the value, and then iterate over them, and use .val()
to extract the value of every element, and treat it as you want.
我认为您必须使用$(".skillLevel")
来选择您想要值的所有元素,然后对其进行迭代,并使用.val()
来提取每个元素的值,并根据需要进行处理。
Hope this helps!
希望这可以帮助!
回答by audrow
You can also use the map
method with an ES6 arrow function like this.
您也可以map
像这样使用带有 ES6 箭头函数的方法。
var arr = $('select.skillLevel').get().map(e => e.value)
As in the accepted answer, arr
is an array of values.
在接受的答案中,arr
是一个值数组。