简体   繁体   中英

How to set selected values on multiple select2?

I have a multiple select2 input. I am populating all necessary options into it. After that I am sending selected values to it but these selected values are not marked on UI.

I tried below code blocks but not working either of them.

let array = [];

  data.jobDepartments.map(x => {
    array.push(x.id);
  });

  $("#jobDepartment").val(array).trigger("change");
let array = [];

  data.jobDepartments.map(x => {
    array.push(x.id);
  });

  $("#jobDepartment").select2("val", array);

Here is my settings for select2 input.

<select id="jobDepartment" name="jobDepartment" class="form-control select2" multiple="multiple" data-toggle="tooltip" data-trigger="hover" data-placement="top" data-title="jobDepartment"></select>
$(document).ready(function () {
  $(".select2").select2();
});
let array = [];

  data.jobDepartments.map(x => {
    array.push(x.id);
  });

  $("#jobDepartment").val(array).trigger("change");

Result is: https://prnt.sc/pn0v94

I was expecting this: https://prnt.sc/pn0vvb

Could you help me with it?

Try this Fiddle

Following things are missing in your code: you should have data config while creating select2

$("#e9").select2({
        placeholder: "Select a State",
        allowClear: true,
    templateSelection:function(obj){
    return obj.title;
    },
        data: [{
                'id': 1,
                title: 'test'
            }, {
                'id': 2,
                title: 'test1'
            }
        ]
    });

then you have fire your change

I solved the problem. Mistake was coming data. My data id was wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM