Set data in Select2 after insert with AJAX

后端 未结 2 636
我在风中等你
我在风中等你 2021-02-05 18:29

i\'m using the Select2 with AJAX (the code below):

$(\".select2-ajax\").select2({
        placeholder: \"Search user\",
        minimumInputLength: 1,
        aj         


        
2条回答
  •  终归单人心
    2021-02-05 18:46

    Starting in v4.x, select2 no longer uses the hidden input field. Instead, you create a new Option and append it to your select element:

    var newOption = new Option(data.name, data.id, true, true);
    $(".select2-ajax").append(newOption).trigger('change');
    

    The combination of the true arguments and trigger('change') will make sure your new is automatically selected after being added.

    See my codepen for a complete working example.

提交回复
热议问题