How to get all options of a select using jQuery?

2019-01-03 07:47发布

How can I get all the options of a select through jQuery by passing on its ID?

I am only looking to get their values, not the text.

14条回答
ゆ 、 Hurt°
2楼-- · 2019-01-03 08:00

$.map is probably the most efficient way to do this.

var options = $('#selectBox option');

var values = $.map(options ,function(option) {
    return option.value;
});

You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.

The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.

查看更多
戒情不戒烟
3楼-- · 2019-01-03 08:00

You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".

A nice way to do this is to use jQuery's $.map():

var selected_val = $.map($("input[name='d_name']:checked"), function(a)
    {
        return a.value;
    }).join(',');

alert(selected_val);
查看更多
萌系小妹纸
4楼-- · 2019-01-03 08:00

You can use following code for that:

var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
    assignedRoleId.push(this.value);
});
查看更多
Melony?
5楼-- · 2019-01-03 08:06

This will put the option values of #myselectbox into a nice clean array for you:

// First, get the elements into a list
var domelts = $('#myselectbox option');

// Next, translate that into an array of just the values
var values = $.map(domelts, function(elt, i) { return $(elt).val();});
查看更多
等我变得足够好
6楼-- · 2019-01-03 08:08

Use:

$("#id option").each(function()
{
    // Add $(this).val() to your list
});

.each() | jQuery API Documentation

查看更多
ゆ 、 Hurt°
7楼-- · 2019-01-03 08:08

This is a simple Script with jQuery:

var items = $("#IDSELECT > option").map(function() {
    var opt = {};
    opt[$(this).val()] = $(this).text();
    return opt;
}).get();
var selectvalues = [];

for(var i = 0; i < items.length; i++) {
    for(key in items[i]) {


        var id = key;
        var text = items[i][key];

        item = {}
        item ["id"] = id;
        item ["text"] = text;

        selectvalues.push(item);

    }
}
console.log(selectvalues);
copy(selectvalues);
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
查看更多
登录 后发表回答