【问题标题】:how to get option value and text of multiselect in jquery如何在jquery中获取多选的选项值和文本
【发布时间】:2019-06-25 20:34:22
【问题描述】:

我想从多选中获取选项和值作为数组

选择框

<div class="form-group" id="specialtyDiv">
   <label class="main">{{__('messages.Speciality')}}</label>
   <div class="input-group">
      {{ Form::select('specialities[]', $speciality_master, old('specialities') ?? '', ['class'=> 'form-control m-select2','id'=>'m_select2_speciality', 'data-plugin'=>'select2','multiple'=>true, 'style'=>'width:100%']) }}
   </div>
</div>  

Jquery 尝试获取选项

$('.select2-tags').on('select2:select', function (e) {
  var specialty = $("#m_select2_speciality");
  var myArray = [];  

  $.each(specialty,function(i,val){
    myArray['text'] = specialty.text();
    myArray['value'] = specialty.val();
  });

  if(isNaN(e.params.data.id)){
      $('#addTagModal').modal();
      $('#addTagModal #tagTitle').val(e.params.data.id);

      $.each(myArray,function(index,json){
            $("#selectSpecialty").append($("<option></option>").attr("value", myArray.value).text(myArray.text));
        });
   }

      });  

我希望 myArray 的输出是这样的

var myArray= [
                  { "value": "pune", "text": "Pune"  },
                  { "value": "mumbai", "text": "Mumbai"  },
                  { "value": "nashik", "text": "Nashik"  }
                ];

请帮我找到解决办法

修改 @Ntiyiso Rikhotso 的回答解决了这个问题,另外,我已经改变了这个

$("#selectSpecialty").append($("<option></option>").attr("value", myArray.value).text(myArray.text));

$("#selectSpecialty").append($("<option></option>").attr("value", data[index].value).text(data[index].text));

【问题讨论】:

标签: jquery html


【解决方案1】:

代码应该为您提供所有选定的选项

var data = [];
$(document).find('#m_select2_speciality option:selected').each(function(){
   var option = $(this);
    data.push({value : option.attr('value'), text : option.text()});
})

console.log(data)

【讨论】:

  • 谢谢,这行得通,但你知道,为什么动态附加的选项显示空值吗?
  • 解决了这个问题,是因为选项附加错误
  • 可以,要处理动态添加的内容,需要使用$(document)
猜你喜欢
  • 2015-03-04
  • 1970-01-01
  • 2021-12-09
  • 2016-12-25
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 2010-11-26
  • 2014-11-02
相关资源
最近更新 更多