【发布时间】: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));
【问题讨论】:
-
这不仅仅是获取文本,而是获取文本和值作为数组