Reputation: 402
I would like to get both options and values from multiselect as an array
select box
<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 which tries fetches the option
$('.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));
});
}
});
I want the output of myArray to be something like this
var myArray= [
{ "value": "pune", "text": "Pune" },
{ "value": "mumbai", "text": "Mumbai" },
{ "value": "nashik", "text": "Nashik" }
];
Please help me find the solution
Edits @Ntiyiso Rikhotso's answer solved the issue, In-addition, I've changed this
$("#selectSpecialty").append($("<option></option>").attr("value", myArray.value).text(myArray.text));
to
$("#selectSpecialty").append($("<option></option>").attr("value", data[index].value).text(data[index].text));
Upvotes: 2
Views: 338
Reputation: 720
The code should get you all the selected options
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)
Upvotes: 2