How to get all selected dropdown list values ​​for a specific id using jQuery

I have a form with several select drop-down menus that start with the id: package, which is dynamically added by the user. My goal is to print all the selected values ​​from these select dropdown lists into an array. Here is the code I have.

 $(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'm doing is pushing selected values ​​into an array, rather than setting values ​​for a specific index. Therefore, if I continue to switch the value for a specific select , I will continue to push the values ​​to the array. How can I determine which selector I am currently finding, so I can get the index in the array to modify the array accordingly?

+4
source share
2 answers

you can use jQuery map() method:

translate all elements in an array or object into a new array of elements.

 $(document).on('change', 'select[id ^="package"]', function() { var arr = $('select[id ^="package"]').map(function(){ return this.id + " " + this.value }) }); 

Demo

+1
source

Is this what you are looking for?

 $(document).on('change', 'select[id ^="package"]', function() { $(this).find('option:selected').each(function(i){ arr[i] = $(this).val(); }); }); 
+1
source

All Articles