0

I cannot understand why Select2 is parsing just the first value of the val() Array. I have tried with Select2 v4.0.3 Whether the count of values in the array, Select2 still show only the first value of the Array.

So, I need to populate Select2 field on Event (modal.open), which is mostly the same as populate Button.on('click').

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

jsfiddle

sealview
  • 99
  • 1
  • 8

2 Answers2

2

Do it this way:

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

Updated jsfiddle

Asad Sarwar
  • 533
  • 3
  • 10
1

The method $("select").select2("val", "1"); is Deprecated instead of using this method try to use the updated one $("select").val("1").trigger("change");

Refer the 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>
vijay
  • 926
  • 7
  • 15