I use remote data source for options. When I load form data from server, it only contains the values of select elements. In such situation, select2 does not know the corresponding text to show to user. Is there any built-in reusable mechanism for this common scenario?
How to set the currently selected value/text when data are fetched using ajax?
$('select#test').select2({
ajax: {
url: "user/combo",
dataType: 'json',
delay: 250,
cache: true
}
});
}
}
Indeed, I am trying to create an angular directive as follow:
app.directive('mehrUserCombo', ['$http', function ($http) {
return {
link: function (scope, element, attr) {
element.select2({
ajax: {
url: "user/combo",
dataType: 'json',
delay: 250,
cache: true
}
});
}
}
Select2 version 2.4 let val, dom = '#your_selector_id'; val = $(dom+' option:selected'). text(); console. log('Initial text is '+val); $(document). on('change', () => { val = $(dom).
Selected items can also be accessed via the :selected jQuery selector: $('#mySelect2'). find(':selected');
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change');
Hiding the search box For single selects, Select2 allows you to hide the search box using the minimumResultsForSearch configuration option. In this example, we use the value Infinity to tell Select2 to never display the search box.
These are your ajax options :
ajax: {
// The number of milliseconds to wait for the user to stop typing before
// issuing the ajax request.
delay: 250,
// You can craft a custom url based on the parameters that are passed into the
// request. This is useful if you are using a framework which has
// JavaScript-based functions for generating the urls to make requests to.
//
// @param params The object containing the parameters used to generate the
// request.
// @returns The url that the request should be made to.
url: function(params) {
return UrlGenerator.Random();
},
// You can pass custom data into the request based on the parameters used to
// make the request. For `GET` requests, the default method, these are the
// query parameters that are appended to the url. For `POST` requests, this
// is the form data that will be passed into the request. For other requests,
// the data returned from here should be customized based on what jQuery and
// your server are expecting.
//
// @param params The object containing the parameters used to generate the
// request.
// @returns Data to be directly passed into the request.
data: function(params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
// You can modify the results that are returned from the server, allowing you
// to make last-minute changes to the data, or find the correct part of the
// response to pass to Select2. Keep in mind that results should be passed as
// an array of objects.
//
// @param data The data as it is returned directly by jQuery.
// @returns An object containing the results data as well as any required
// metadata that is used by plugins. The object should contain an array of
// data objects as the `results` key.
processResults: function(data) {
return {
results: data
};
},
// You can use a custom AJAX transport function if you do not want to use the
// default one provided by jQuery.
//
// @param params The object containing the parameters used to generate the
// request.
// @param success A callback function that takes `data`, the results from the
// request.
// @param failure A callback function that indicates that the request could
// not be completed.
// @returns An object that has an `abort` function that can be called to abort
// the request if needed.
transport: function(params, success, failure) {
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
on the processResult function use :
processResults: function(data) {
$('select#test').select2("val", YOUR VALUE FROM PROCESSED DATA); //set the value
return {
results: data
};
}
You can use the data & results functions within your ajax call to request, parse, and set your json data dependent on your data.
Here's a small code snippet from some of my production code that does something similar to what you're asking:
$(".autocomplete-search").select2({
placeholder: "Pizza, Movies, etc...",
minimumInputLength: 2,
ajax: {
url: '/find-suggestions.json',
dataType: 'json',
quietMillis: 250,
data: function(params, page) {
return {
query: params,
page: page
};
},
results: function(data, page) {
var more, search_all, searched_for;
searched_for = $(".select2-search input").val();
search_all = [
{
query: searched_for
}
];
more = data.suggestions.stores.length >= 1;
return {
results: search_all.concat(data.suggestions.categories, data.suggestions.stores),
more: more
};
}
}
});
In data:
I'm using the params
value to pass the original value to my ajax api, then in the results:
returning the data; I can get the original input value (searched_for
) and pair it with other data below, parsing it out and concatenating it as seen in the example.
I don't know how to give you the exact answer you are looking for without more detail, but I believe the code snippet illustrates the types of behaviors you are trying to accomplish. Also, I just noticed @prollyGeek's answer came through as I was typing this, read the docs in the comments as well, quite helpful.
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