Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert all items (options) of a multi select dropdown into an array using jquery

I am trying to convert a multiple select dropDown values (all options) into an array using jquery.

<select size="10" style="width: 330px;" name="itemList"
        id="selectedItemLists" multiple="multiple">
    <option value="1">value1</option>
    <option value="2">value2</option>
    <option value="3">value3</option>
    <option value="4">value4</option>
</select>

Now using jquery how to create an array like array[0]=value1,array[1]=value2...

Please help me in this.

Thanks in advance.

like image 661
Satya Avatar asked Dec 16 '22 14:12

Satya


2 Answers

Possibly something like:

var options = new Array();
$('#selectedItemLists > option:selected').each(
     function(i){
         options[i] = $(this).val();
     });

JS Fiddle demo.


Edited in response to @mellamokb's comment, to amend the jQuery to use text() instead of val():
var options = new Array();
$('#selectedItemLists > option:selected').each(
     function(i){
         options[i] = $(this).text();
     });

JS Fiddle demo.

References:

  • :selected selector.
  • each().
  • val().
  • text().
like image 66
David Thomas Avatar answered Dec 24 '22 14:12

David Thomas


You can use .map() to accomplish this as well.

var i = $.map($("#selectedItemLists option:selected"), function(elem){
    return $(elem).text();
});

Example on jsfiddle

like image 35
Mark Coleman Avatar answered Dec 24 '22 15:12

Mark Coleman