开发者

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" mu开发者_JAVA百科ltiple="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:

  • :selected selector.
  • each().
  • val().
  • text().


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜