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.