Search code examples
jqueryjquery-select2

Add selected options to Select2


I'm using Select2 in "Ajax mode" so I get the options from an API endpoint. But I need to prefill it with some selected options via Javascript after the user starts to type.

I've try to append it to the <select></select> and also to the rendered list, but I can't get it right.


Solution

  • In case that someone is struggling with the same

    var option = new Option("text", "id");
    option.selected = true;
    
    $("#id").append(option);
    $("#id").trigger("change");
    

    jsFiddle