27

我在多选中获取所有选定选项时遇到问题

<select multiple="" title="" class="" id="fm_delivery_or_collection" name="fm_fields[fm_delivery_or_collection][]">
  <option value="90">Delivery or Collection1</option>
  <option value="91">Delivery or Collection2</option>
  <option value="92">Delivery or Collection3</option>
</select>

贝娄是我的代码,它只返回我第一个选择的选项

var select = form.find('select')

for (var i = 0; i < select.length; i++) 
        {
            var s_id = jQuery(select[i]).attr('id');
            var str="",i;

            var e = document.getElementById(s_id);
            var strUser = e.options[e.selectedIndex].text;

            var name = jQuery(select[i]).attr('name')
            var str1 = jQuery(select[i]).attr('id').replace("fm_"," ")
            requestString += "<b>"+str1.replace(/_/g," ")+"</b>" + ':' +strUser+"<br>";
        }

所以请建议我如何获取所有选定的选项文本以及我在哪里出错?

4

7 回答 7

47

你的评论please suggest me how can i get all selected option text所以你可以试试这个

$("#fm_delivery_or_collection option:selected").each(function () {
   var $this = $(this);
   if ($this.length) {
    var selText = $this.text();
    console.log(selText);
   }
});
于 2013-02-20T06:00:12.963 回答
34

立即完成所有操作

var text = $('#selector option:selected').toArray().map(item => item.text).join();

它像这样返回:

text1,text2,text3,text4
于 2018-08-17T13:50:54.903 回答
13
// Return an array of the selected opion values
// select is an HTML select element
function GetSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}

将此功能传递给您的选择框,就像..

var selectBox = document.getElementsById('fm_delivery_or_collection');
alert(GetSelectValues(selectBox ));

它将返回所选值的数组

通过使用 Jquery

$('select#fm_delivery_or_collection').val()

如果它是一个倍数,则从 调用的val函数select将返回一个数组。

于 2013-02-20T05:28:07.637 回答
2

试试这个

$("#fm_delivery_or_collection option").each(function(){
    if($(this).attr('selected') == 'selected')
    {
        var name = $("#fm_delivery_or_collection").attr('name')
        var str1 = $("#fm_delivery_or_collection").attr('id').replace("fm_"," ")
        requestString += "<b>"+str1.replace(/_/g," ")+"</b>" + ':' +strUser+"<br>";
     }
})
于 2013-02-20T05:16:03.677 回答
2
 $("#id :selected").each(function (i,sel) {
   alert($(sel).text());
 });

希望能帮助到你..

于 2015-11-20T08:18:32.433 回答
2

只需添加这行代码:-

var reciever= jQuery('#to_select option:selected').toArray().map(item => item.text).join();
/* alert(reciever); */
于 2019-06-11T06:47:00.500 回答
1

试试这个链接

$("#selection option:selected").each(function () {
   var $this = $(this);
   if ($this.length) {
    var selText = $this.text();
    console.log(selText);
    $('#selected').append(selText+', ');
  }
});
于 2017-02-22T08:00:04.730 回答