'select2 automatically select item for ajax call
Is there a way to make select2 control auto select an item when ajax response contain extra data.
I want to implement my controller to in JsonResult mark item as exact mach and then to select2 control automatic select that without opening drop n down.
From user prespecitve: If user type in select2 textbox string that exactly match item on controller. e.g. If user type in barcode and controller method find that bar-code. Select2 control will immediately select that item without opening dropdown.
If user type in query that is not exactly match controller will return list of items without param exact and select2 will open dropdown to show user possible choice of items.
Solution 1:[1]
#this worked for me... using select2 with barcode
var defaultInitialGroup = '';
$("#idbarang").select2({
placeholder: "Type/ Scan your barcode item",
allowClear: true,
minimumInputLength: 2,
multiple: true,
ajax: {
url: HOST_URL + 'stock/balance/list_xxv',
type: 'POST',
dataType: 'json',
delay: 250,
data: function(params) {
return {
_search_: params.term, // search term
_page_: params.page,
_draw_: true,
_start_: 1,
_perpage_: 2,
_paramglobal_: defaultInitialGroup,
term: params.term,
};
},
processResults: function (data, params) {
var searchTerm = $("#idbarang").data("select2").$dropdown.find("input").val();
if (data.items.length === 1 && data.items[0].text === searchTerm) {
var option = new Option(data.items[0].nmbarang, data.items[0].idbarang, true, true);
$('#idbarang').append(option).trigger('change').select2("close");
// manually trigger the `select2:select` event
$('#idbarang').trigger({
type: 'select2:select',
params: {
data: data
}
});}
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: false
},
escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
templateResult: formatItem, // omitted for brevity, see the source of this page
templateSelection: formatItemSelection // omitted for brevity, see the source of this page
})
function formatItem(repo) {
if (repo.loading) return repo.text;
var markup ="<div class='select2-result-repository__description'>" + repo.idbarang +"<i class='fa fa-circle-o'></i>"+ repo.nmbarang +"</div>";
return markup;
}
function formatItemSelection(repo){
return repo.nmbarang || repo.text;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fiky Ashariza |
