问题
i'm using the Select2 with AJAX (the code below):
$(".select2-ajax").select2({
placeholder: "Search user",
minimumInputLength: 1,
ajax: {
url: $('#url-search-client').val(),
dataType: 'json',
type: 'post',
data: function (term, page) {
return {
filter: term
};
},
results: function (data, page) {
return {results: data};
}
},
width : '50%',
formatInputTooShort: function () {return 'Informe mais caracteres'; },
formatResult: formatResultSelectAjax, // omitted for brevity, see the source of this page
formatSelection: formatSelectAjaxValue, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
});
Well, if not found client, the user can be use a button to open a modal and add the new client, is possible use the return(json with id and namae) of new client and put the data (like name) into the select2 as selected?
$('.btn-form-client').click(function() {
$.ajax({
url: $('#frm-client').attr('action'),
dataType: 'json',
type: 'post',
data: $('#frm-client').serialize()
}).done(function (data) {
$('#modal-client').modal('hide')
});
return false;
});
回答1:
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.
回答2:
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});
来源:https://stackoverflow.com/questions/14311657/set-data-in-select2-after-insert-with-ajax