Set data in Select2 after insert with AJAX Set data in Select2 after insert with AJAX ajax ajax

Set data in Select2 after insert with AJAX


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.


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});