0

My select2 dropdown contains the following two options:

Carbon
Stainless

I can manually put one option into its container with:

var myoption = 'Carbon'
$(TabTagBox).val([myoption]).trigger('change.select2');

But what is the correct syntax for using the above line with append?

Silverburch
  • 457
  • 2
  • 12
  • 28

2 Answers2

0

The documentation has a specific section for programmatically interacting with the select2 plugin and the first example is what you want (see https://select2.org/programmatic-control/add-select-clear-items)

var data = {
    id: 1,
    text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • No, I'm not asking about appending new options to the dropdown. I'm asking about appending the options to its select2 container. – Silverburch Apr 14 '18 at 19:52
  • the select2 container needs an underlying dropdown to match. So adding it to the dropdown and calling the change will update the select2 by appending the new options to it as well. – Gabriele Petrioli Apr 14 '18 at 20:04
  • @Silverburch is it a multiselect where you show the selected options as tags ? – Gabriele Petrioli Apr 14 '18 at 20:15
  • Exactly. You see, I've already got all the options in the dropdown. I'm trying to manually move particular selected options from the dropdown to the container (inside a loop). Putting one option there is easy. But I'm not able to put multiple options into the container – Silverburch Apr 14 '18 at 20:19
  • @Silverburch then in your loop you should not actually call the `.val` on the select2, but instead just add items in an array and after the loop use `.val( arrayWithAllSelection ).trigger..`. If you could post more of your code i could suggest an actual fix. – Gabriele Petrioli Apr 14 '18 at 20:30
  • Many thanks, this really helps. Unfortunately my code is complex as it's based around authentications with external files being looked-up. Trying to condense that into a simple but meaningful fiddle right now will do my head in! I'll try to follow what you suggest and if I fail perhaps I'll try the fiddle after all and appeal to you again. Much appreciated. – Silverburch Apr 14 '18 at 20:43
0

the select2 container needs an underlying dropdown to match. So adding it to the dropdown and calling the change will update the select2 by appending the new options to it as well. –

I also wanted to change all the Options of dropdown, above comment solved my problem. Thanks