问题
I have the following multi-select picker which is populated with data. I want to be able to set multiple selected values that I get from the database.
<div class="form-group col-md-6 col-lg-6 col-sm-6">
<label>Choose Skills</label>
<select id="DDLSkills" name="selValue" data-live-search="true" data-style="btn-default form-control" class="selectpicker form-control" data-size="5" multiple data-max-options="2"></select>
</div>
This is the code that I use to populate the multi-select picker:
$('.selectpicker').selectpicker();
$.ajax({
type: "POST",
url: '/TutorSkills/FetchTutorSkills',
success: function (data) {
//console.dir(data);
for (var i = 0; i < data.length; i++) {
$("#DDLSkills").append('<option data-tokens="' + data[i].Skill.SkillName + '" value="' + data[i].Skill.Id + '">' + data[i].Skill.SkillName + '</option>');
}
$("#DDLSkills").selectpicker("refresh");
},
error: function (error) {
alert('Failed to get the logged-in tutor skills!');
}
})
However, I want to be able to set selected values that I get from the database but the code below only sets the last value that I get from the database.
$.ajax({
type: "POST",
url: '/ClassSkills/GetClassSelectedSkills',
data: { 'id': selectedEvent.id },
success: function (data) {
console.dir(data);
for (var i = 0; i < data.length; i++) {
$('.selectpicker').selectpicker('val', [data[i].Skill.Id]);
}
$('.DDLSkills').selectpicker('refresh')
},
error: function (error) {
alert('Failed');
}
})
Thank you
回答1:
Try if this work
$.ajax({
type: "POST",
url: '/ClassSkills/GetClassSelectedSkills',
data: { 'id': selectedEvent.id },
success: function (data) {
console.dir(data);
let optArr = [];
for (var i = 0; i < data.length; i++) {
optArr.push(data[i].Skill.Id);
}
$('.selectpicker').selectpicker('val', optArr);
$('.DDLSkills').selectpicker('refresh')
},
error: function (error) {
alert('Failed');
}
})
来源:https://stackoverflow.com/questions/49718354/how-to-set-multiple-selected-values-for-multi-select-picker