简体   繁体   中英

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.

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:

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

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

Example on jsfiddle

The jQuery map method is useful here.

$('select option').map(function(index, elem){
    return $(elem).text();
});

(Mark beat me to it, but mine uses the map method of the collection rather than the "static" jQuery.map function. Both are fine, of course.)

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