javascriptajaxjquery-select2jquery-select2-4

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

  • 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
      }
    });