Невозможно выбрать недавно добавленные компоненты selectize после вызова ajax

Невозможно выбрать недавно добавленные компоненты selectize для отправки вызова ajax

Я предварительно заполнил параметры текущими выбранными параметрами и пытаюсь получить дополнительные параметры с помощью вызова ajax с сервера. Мой сервер возвращает такие данные, но я не уверен, что делать с этими данными

[{"id":303,"name":"Short Sleeve Opening"}]

Я пробовал использовать методы addOption и refreshOptions, но они, похоже, не работают. Ниже приведен фрагмент кода, который вызывает компонент selectize.

$(function () {
    $select_options = $('select').selectize({
        plugins: ['restore_on_backspace', 'remove_button', 'drag_drop'],
        delimiter: ',',
        persist: false,
        create: function (input) { // I am not sure if this is of any use, as I never found the control to enter in this part of  code during debugging.
            return {
                value: input,
                text: input
            }
        },
        load: function (query, callback) {
            if (!query.length) return callback();
            $.ajax({
                dataType: 'json',
                url: '/measurement_tags/autocomplete_key?q=' + encodeURIComponent(query),
                error: function () {
                    callback();     //Not sure what the callback should be, documenation is not self explanatory
                },
                success: function (res) {
                //Added this callback to add the new options to the list, it is adding the new options to the list but I can't select them at all
                //Moreover, second time I try to use autocomplete it doesn't work. The control doesn't reach the load method, and no error observed in console
                    for (index in res) {
                        $('.selectize-dropdown-content').append('<div class="option" data-selectable="" data-value="' + res[index].id + ' ">' + res[index].name + '</div>');
                    }
                }
            });
        }
    });
});

Каков точный способ добавить новые параметры в список на постоянной основе?


person vipin8169    schedule 23.05.2016    source источник


Ответы (1)


Наконец-то добился этого, потратив целый день:

$(function () {
    $select_options = $('select').selectize({
        plugins: ['restore_on_backspace', 'remove_button', 'drag_drop'],
        delimiter: ',',
        persist: false,
        options: [],
        load: function (query) {
            $.ajax({
                dataType: 'json',
                url: '/measurement_tags/autocomplete_key?q=' + encodeURIComponent(query),
                success: function (res) {
                    updateOptions(res);
                }
            });
        }
    });
    var updateOptions = function (newOptions) {
        var selectize = $select_options[0].selectize;
        for (index in newOptions) {
            selectize.addOption({
                value: newOptions[index].id,
                text: newOptions[index].name,
            });
        }
        selectize.refreshOptions();
    }
});
person vipin8169    schedule 23.05.2016