最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get all values in a dropdown select menu? - Stack Overflow

programmeradmin0浏览0评论

I know how to get the selected value in an html dropdown menu using jquery.

However, I want to get an array of all values in the dropdown (i.e. and array containing the value of each <option> tag in the <select>), regardless of what is selected or not. What is the proper way to do this?

I know how to get the selected value in an html dropdown menu using jquery.

However, I want to get an array of all values in the dropdown (i.e. and array containing the value of each <option> tag in the <select>), regardless of what is selected or not. What is the proper way to do this?

Share Improve this question asked Apr 25, 2011 at 19:04 johnjohn 2,8516 gold badges25 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Pretty simple, using some selectors and an $.each:

$('select#id_of_select_if_you_want option').each(function(idx, val)
{
    $(val).val(); // here's the value
    $(val).html(); // here's the display text
});

To get an array of something based on a set of elements, use $.map():

var arrayOfValues = $("#mySelect option").map(function() { return this.value; });

I can't ment on gilly3 (someone with the reputation could help?). His response will give you an object literal, not an array.

If you want an array of values, you can do a map like he suggests, but you need to append the values to a list instead. Here's my version (I'm sure it can be improved):

var all_values = [];
$('#dropdown option').map( function() { 
    if (this.value.length) { 
       all_values.push(this.value)
    }
});

EDIT:

It looks like, you can use gilly3's answer, but, if you want to actually use the return as an array, you need to append a .get() method.

$('#dropdown option').map( function() {return this.value}).get();
发布评论

评论列表(0)

  1. 暂无评论