How to set multiple selected values for multi-select picker?

杀马特。学长 韩版系。学妹 提交于 2021-01-28 09:10:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!