我如何通过jQuery传递它的ID来获得一个选择的所有选项?

我只是想获取它们的值,而不是文本。


当前回答

这是一个简单的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>

其他回答

这将把#myselectbox的选项值放入一个整洁的数组中:

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

// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$('select#id').find('option').each(function() {
    alert($(this).val());
});

另一种方法是使用toArray(),以便使用胖箭头函数与map,例如:

const options = $('#myselect option').toArray().map(it => $(it).val())

您可以根据复选框的名称获取所有“选定值”,并将它们显示在以“,”分隔的字符串中。

一个很好的方法是使用jQuery的$.map():

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

alert(selected_val);
    var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +'  value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
            });
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);