简体   繁体   中英

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. My goal is to put all the selected values from these select dropdowns into an array. 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. 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:

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
    })
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM