如何在jQuery中获取选项值和multiselect文本

时间:2019-06-25 12:03:47

标签: jquery html

我想从multiselect中同时获取选项和值作为数组

选择框

<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));

1 个答案:

答案 0 :(得分:2)

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

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)