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;
});
// Set up the Select2 control $('#mySelect2').select2({ ajax: { url: '/api/students' } }); // Fetch the preselected item, and add to the control var studentSelect = $('#mySelect2'); $.ajax({ type: 'GET', url: '/api/students/s/' + studentId }).then(function (data) { // create the option and append to Select2 var option ...
HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.
Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.
AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With