Select2 预选 val 数组只解析数组的第一个值

Select2 preselect val array parse just first value of array

我不明白为什么 Select2 只解析 val() 数组的第一个值。我试过 Select2 v4.0.3 无论数组中值的计数,Select2 仍然只显示数组的第一个值。

因此,我需要在事件 (modal.open) 上填充 Select2 字段,这与填充 Button.on('click').

基本相同
var checkList = [2, 4, 5, 7];
$("#update").on('click', function() {
  $("#list").select2().select2('val', checkList);
})

jsfiddle

这样做:

  var checkList = [2, 4, 5, 7];
  $("#update").on('click', function() {
        $("#list").val(checkList).trigger("change");
  });

Updated jsfiddle

方法 $("select").select2("val", "1"); 已弃用而不是使用此方法尝试使用更新的方法 $("select").val("1").trigger("change");

参考link https://select2.github.io/announcements-4.0.html#removed-methods

$(document).ready(function() {
  $("#list").select2({
    maximumSelectionLength: 4,
    placeholder: "Click 'Update'",
    allowClear: true,
    data: [{
      id: 1,
      text: "ABBOUD NIDAL"
    }, {
      id: 2,
      text: "ABDULLA AMER-RAUL"
    }, {
      id: 3,
      text: "AL MOMANI RACAN"
    }, {
      id: 4,
      text: "ALEXANDRESCU BOGDAN"
    }, {
      id: 5,
      text: "ALEXANDRU DARIA MARIA"
    }, {
      id: 6,
      text: "ANASTASE ANTONIA"
    }, {
      id: 7,
      text: "ANGHEL DIANA"
    }, {
      id: 8,
      text: "AROSCULESEI IONUT"
    }, {
      id: 9,
      text: "ASANDEI ANDREI"
    }, {
      id: 10,
      text: "AXINTE ANDREEA GABRIELA"
    }, {
      id: 11,
      text: "BADESCU IOANA"
    }, {
      id: 12,
      text: "BALACI SEBASTIAN"
    }, {
      id: 13,
      text: "BANI-MENYAH LARA"
    }, {
      id: 14,
      text: "BEJENARU ANDREI"
    }, {
      id: 15,
      text: "BERBECEL ALEXANDRU"
    }, {
      id: 16,
      text: "CANAL ALEXANDRE"
    }, {
      id: 17,
      text: "CAPILNEAN ADINA"
    }, {
      id: 18,
      text: "CHECHERITA EDUARD ANDREI"
    }, {
      id: 19,
      text: "CIOBANU CATALIN GABRIEL"
    }, {
      id: 20,
      text: "CIUCU TUDOR ANDREI"
    }]
  });
  var checkList = ["2", "4", "5", "7"];
  $("#update").on('click', function() {
    $("#list").val(checkList).trigger("change");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<select multiple="multiple" id="list" name="nombres">
</select>
<br>
<button id="update">Update</button>