无法在ajax调用后选择新添加的选择组件

时间:2016-05-23 13:51:21

标签: javascript ruby-on-rails-4.2 selectize.js

无法在ajax调用

后选择新添加的selectize组件

我已预先使用当前选定的选项填充选项,并尝试使用服务器的ajax调用检索更多选项。 我的服务器返回这样的数据,但我不知道如何处理这些数据

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

我尝试过使用addOption和refreshOptions方法,但它们似乎无法正常工作。 下面是调用选择组件的代码段。

$(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>');
                    }
                }
            });
        }
    });
});

将新选项永久添加到列表的确切方法是什么?

1 个答案:

答案 0 :(得分:0)

最后在浪费了一整天后实现了这个目标:

$(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();
    }
});