简体   繁体   中英

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.

eg If user type in barcode and controller method find that bar-code. Select2 control will immediately select that item without opening dropdown.

To do this with AJAX, you need to add a selected option to the select DOM element, and then trigger a change on the select2 widget so it redraws. Below may be what you are looking for. This example uses processResults to check to see if there is exactly one match and it matches what the user typed exactly.

$("#product_id").select2({
  ajax: {
    url: "/api/productLookup",
    dataType: 'json',
    data: function (params) {
      return {
        term: params.term,
        };
    },
    processResults: function (data) {
        var searchTerm = $("#product_id").data("select2").$dropdown.find("input").val();
        if (data.results.length == 1 && data.results[0].text == searchTerm) {
            $("#product_id").append($("<option />")
                .attr("value", data.results[0].id)
                .html(data.results[0].text)
            ).val(data.results[0].id).trigger("change").select2("close");
        }
        return data;
    },
    minimumInputLength: 8,
    cache: true
  }
});
#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM