10

This seems like a standard thing to want to do, but I'm struggling to find a clear and simple solution.

I want to be able to add one or more additional options to an already initialized Select2.

I am using an older version of Select2, not sure what the version is off hand though.

Stewart Alan
  • 1,521
  • 5
  • 23
  • 45

4 Answers4

23

You can solve most questions involving Select2 in the same way that they would be solved in a standard <select>. In this case, the corresponding <select> question would be: Adding options to select with javascript.

var option = new Option("text", "id");
$("select").append(option);

If you want it to be selected when it is inserted, you can just set the selected property on the new option.

var option = new Option("text", "id");
option.selected = true;

$("select").append(option);
$("select").trigger("change");

Note that I also triggered the change event so that Select2 can know that the selected options have changed.

Community
  • 1
  • 1
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
  • Kevin, i have raised a question for select2. it seems like you have a good experience in it and you can solve the issue. I tried multiple times but its not working. If possible could you please look at this one. http://stackoverflow.com/questions/35729864/jquery-select2-selected-value-from-database-by-ajax – Roxx Mar 01 '16 at 18:52
  • Thank you, exactly what I've needed! – Szabi Zsoldos Jan 11 '19 at 11:44
11

God I should stop to think before posting sometimes.

Its as simple as just adding a new option to the underlying select:

$("#myselect").append($('<option>', {value: 1, text: 'new option'}));

Don't even need to re-initialize the select2.

LeftyX
  • 35,328
  • 21
  • 132
  • 193
Stewart Alan
  • 1,521
  • 5
  • 23
  • 45
1

I solved this problem with "Data" property of select2. Firstly, I got data with json and then I create my select2 element with my array as below.

corrCodeArray is my json array.

function fillSelectReportPeriod() {
var corrCodeArray = retrieveCorrCodes();
$(".js-example-basic-multiple").select2({
    maximumSelectionLength: 4,
    data: corrCodeArray
});    

}

Note: When I give select2 element name like $("#selectReportPeriod") instead of $(".js-example-basic-multiple") it didn't work so I used class name.

Alex Ciocan
  • 2,272
  • 14
  • 20
Engin Aydogdu
  • 190
  • 1
  • 8
-1

This works for me:

$("#company_dealer").val('Newly Selected Dealer').trigger('change');
Sinan Eldem
  • 5,564
  • 3
  • 36
  • 37