Set data in Select2 after insert with AJAX

后端 未结 2 637
我在风中等你
我在风中等你 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:43

    I managed to make it work. After POST in jQuery, i get a JSON with the new data and set the hidden input and the select ('.select2-ajax')

    $('#client=id').val(data.id);
    $('#modal-solicitante').modal('hide'); //This is my
    $(".select2-ajax").select2('data', {id: data.id, name: data.name, email: data.email});
    
    0 讨论(0)
  • 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 <option> is automatically selected after being added.

    See my codepen for a complete working example.

    0 讨论(0)
提交回复
热议问题