我有以下多选选择器,其中填充了数据。我希望能够设置从数据库中获取的多个选定值。
<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>
这是我用来填充多选选择器的代码:
$('.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!');
}
})
但是,我希望能够设置从数据库中获取的选定值,但下面的代码仅设置从数据库中获取的最后一个值。
$.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');
}
})
谢谢
答案 0 :(得分:2)
尝试这项工作
$.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');
}
})