[英]How to get all selected dropdown values for a particular Id using Jquery
I have a form with multiple select
dropdown menus that start with the id: package which are added dynamically by the user. 我有一个带有多个
select
下拉菜单的表单,这些菜单以id:包开头,由用户动态添加。 My goal is to put all the selected values from these select
dropdowns into an array. 我的目标是将所有这些
select
下拉列表中的所有选定值放入数组中。 Here is the code I have so far. 这是我到目前为止的代码。
$(document).ready(function() {
arr = new Array();
$(document).on('change', 'select[id ^="package"]', function() {
arr.push($(this).val());
alert(arr.join('\n')); //for testing
});
});
Currently all I am doing is pushing the selected values onto the array rather than setting the values for a specific index. 目前,我要做的只是将选定的值推送到数组上,而不是为特定索引设置值。 Therefore if I keep switching the value for a specific
select
, I will keep pushing values onto the array. 因此,如果我继续为特定的
select
切换值,我将继续将值压入数组。 How can I determine which selector I am currently in so I can get an index into the array to modify the array accordingly? 如何确定当前使用的选择器,以便可以在数组中获取索引以相应地修改数组?
is this what you're looking for? 这是您要找的东西吗?
$(document).on('change', 'select[id ^="package"]', function() {
$(this).find('option:selected').each(function(i){
arr[i] = $(this).val();
});
});
you can use jQuery map()
method: 您可以使用jQuery
map()
方法:
translate all items in an array or object to new array of items.
将数组或对象中的所有项目转换为新的项目数组。
$(document).on('change', 'select[id ^="package"]', function() {
var arr = $('select[id ^="package"]').map(function(){
return this.id + " " + this.value
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.