select2 отображать параметр по умолчанию (статический) и выполнять поиск ajax, если он не найден

У меня есть select2 v4 со статическим выбором (100 вариантов). Когда пользовательский ввод не найден в списке параметров по умолчанию, мне нужно выполнить поиск ajax.

Поскольку мне не удалось использовать один и тот же объект выбора, я использую другой для поиска ajax. Поэтому я скрываю выбор по умолчанию и заменяю его на ajax_select. Сделайте ajax-поиск.

код:

<script type="text/javascript">

    var s2_search =''; //global var for search string

    $("#default_select").select2({
        placeholder: "Select an item",
        debug: true,
        minimumInputLength: 0, // important!!! => without setting to 0 the default data will not be shown

        tags:true,
        createTag: function (params) {
            s2_search = params.term; //assing search string to var
        },

        templateResult: function(data){

            var $result = $("<span></span>");

            $result.text(data.text);

            return $result;
        },
        escapeMarkup: function (markup) {
            if(markup == 'No results found'){
               // item is not found in default activate the ajax select
                $('#div_default').addClass('hidden');
                $('#div_new').removeClass('hidden');
                new_select_func(s2_search)
            }
            else {
                return markup;
            }
        }
    });

    var $myselect = $('#new_select').select2({
        minimumInputLength: 0,
        ajax: {
            url: BASE_URL + '/get_more',
            dataType: 'json',
            cache: true,
            delay: 350,
            data: function (params) {
                return {
                    q: params.term//, // search term
                };
            },
            processResults: function (data, params) {
                if(data === false){
                    // if the item is not found in the database display a modal form to insert the item
                    // This works 
                    $.get(BASE_URL+'/get_new_form',{plate: params.term}, function (data) {
                        $('#myModal').find('.modal-body').html(data);
                    });
                    $('#myModal').modal('show');
                }
                else {
                    return {
                        results: data 
                    };
                }
            }
        },
        templateSelection: formatNewSelection 

    });

    function formatNewSelection(data, container) {

        // append the new item to the default select
        $("#default_select").append($('<option>', {value: data.id, text: data.text}));
        //restore default select 
        $('#div_default').removeClass('hidden');
        // hide new select
        $('#div_new').addClass('hidden');

        return data.text;
    }
    function new_select_func(search_val) {
        //close default select 
        $("#default_select").select2("close");
        //open new select 
        $myselect.select2('open');
        // set search string and trigger ajax search
        var $search = $myselect.data('select2').dropdown.$search || $myselect.data('select2').selection.$search;
        $search.val(search_val);
        $search.trigger('keyup');

    }
</script>

Определенно не лучший способ сделать это, но у меня есть только одна проблема. Когда я выбираю элемент в ajax_select, чтобы добавить его по умолчанию, выберите его, чтобы создать один и тот же параметр 4 раза. Может ли кто-нибудь сказать мне, почему и есть ли лучший способ сделать это?

Спасибо, Салейн.


person Salain    schedule 07.07.2016    source источник


Ответы (1)


Я разрешил множественный вариант, добавленный к default_select при выборе в ajax_select (new_select). Проблема была с функцией templateSelection formatNewSelection, я заменил ее событием select2:select.

Код для new_select :

var $myselect = $('#new_select').select2({
    minimumInputLength: 0,
    ajax: {
        url: BASE_URL + '/get_more',
        dataType: 'json',
        cache: true,
        delay: 350,
        data: function (params) {
            return {
                q: params.term//, // search term
            };
        },
        processResults: function (data, params) {
            if(data === false){
                // if the item is not found in the database display a modal form to insert the item
                // This works 
                $.get(BASE_URL+'/get_new_form',{plate: params.term}, function (data) {
                    $('#myModal').find('.modal-body').html(data);
                });
                $('#myModal').modal('show');
            }
            else {
                return {
                    results: data 
                };
            }
        }
    } 
   // the Selection template and function are not needed using default format
   //,templateSelection: formatNewSelection 

});

$myselect.on("select2:select",  function(e) {

    // append the new item to the default select
    $("#default_select").append($('<option>', {value: e.params.data.id, text: e.params.data.text}));
    //restore default select 
    $('#div_default').removeClass('hidden');
    // hide new select
    $('#div_new').addClass('hidden');

});

Это все еще не лучшая часть кодирования, но пока она работает. Любая помощь в улучшении этого будет в основном оценена.

person Salain    schedule 08.07.2016