Home > Back-end >  Can't pre-select options in Select2 multiple choice select box
Can't pre-select options in Select2 multiple choice select box

Time:01-11

I use the select2 jQuery module to create a multiple choice select box. I did this in an early version (3.4.5) and it worked fine. But after upgrade to 4.1.0 pre-selection of an option does not work.

My code looks like below,

HTML - part:

<input type="text" id="accessories" />

JS:

jQuery(document).ready(function() {
   var acceArray2 = [{id:0,text:"textA"},{id:1,text:"textB"},{id:2,text:"textC"}];
        
   jQuery("#accessories").select2({
                        data: acceArray2,
                        multiple: true,
                        placeholder: "",
                        width: 200
                    });
   jQuery("#accessories").val("1");
   jQuery("#accessories").trigger("change");
});

My options show up when I click in the box. I can also select one or more option. But I expect "textB" should be selected when I open the page. This works fine with the original select2 version, but not with 4.1.0. The box is just empty.

I have spent hours trying to figure what's wrong, but I can't....

CodePudding user response:

Alternatively, you can change the input tag to select. It seems to work below:

jQuery(document).ready(function() {
  const acceArray2 = [{
    id: 0,
    text: "textA"
  }, {
    id: 1,
    text: "textB"
  }, {
    id: 2,
    text: "textC"
  }];

  jQuery("#accessories").select2({
    data: acceArray2,
    multiple: true,
    placeholder: "",
    width: 200
  });
  jQuery("#accessories").val("1");
  jQuery("#accessories").trigger("change");

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<select id="accessories" />

CodePudding user response:

You can add selected option in array object like:

jQuery(document).ready(function() {
  var acceArray2 = [{
    id: 0,
    text: "textA"
  }, {
    id: 1,
    text: "textB",
    selected: true
  }, {
    id: 2,
    text: "textC",
    selected: true
  }];

  jQuery("#accessories").select2({
    data: acceArray2,
    multiple: true,
    placeholder: "",
    width: 200
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<input type="text" id="accessories" />

  •  Tags:  
  • Related