Set data in Select2 after insert with AJAX

天涯浪子 提交于 2019-12-03 07:17:49

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});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!