Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add options to Select2 after inititialzation

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.

like image 469
Stewart Alan Avatar asked Apr 13 '15 11:04

Stewart Alan


2 Answers

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.

like image 120
Stewart Alan Avatar answered Oct 20 '22 22:10

Stewart Alan


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.

like image 36
Kevin Brown-Silva Avatar answered Oct 20 '22 21:10

Kevin Brown-Silva