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

时间:2016-12-19 07:09:02

标签: javascript jquery arrays select2

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

所以,我需要在Event(modal.open)上填充Select2字段,这与填充Button.on(' click')大致相同。

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

jsfiddle

2 个答案:

答案 0 :(得分:2)

这样做:

id="variabile_id"

Updated jsfiddle

答案 1 :(得分:1)

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

请参阅链接 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>
&#13;
&#13;
&#13;