javascript - 使用 jQuery Select2 清除下拉列表

标签 javascript jquery jquery-select2

我正在尝试使用出色的 Select2 以编程方式清除下拉列表图书馆。下拉列表使用 Select2 query 选项动态填充远程 ajax 调用。

HTML:

<input id="remote" type="hidden" data-placeholder="Choose Something" />

Javascript:

        var $remote = $('#remote');

        $remote.select2({
            allowClear: true,
            minimumInputLength: 2,
            query: function(options){
                $.ajax({
                    dataType: 'json',
                    url: myURL + options.term,
                    error: function(jqXHR, textStatus, errorThrown){
                        smoke.alert(textStatus + ": server returned error on parsing arguments starting with " + options.term);
                    },
                    success: function(data, textStatus, jqXHR){
                        var results = [];
                        for(var i = 0; i < data.length; ++i){
                            results.push({id: data[i].id, text: data[i].name});
                        }

                        options.callback({results: results, more: false});
                    }
                });
            }
        });

不幸的是,调用 $remove.select2('val', '') 会抛出以下异常:

 Uncaught Error: cannot call val() if initSelection() is not defined

我试过设置 attr、设置 valtext 和 Select2 特定的 data 函数.似乎无法让这个人清楚并以单选按钮的方式工作。有人有建议吗?

最佳答案

这对我有用:

 $remote.select2('data', {id: null, text: null})

当您以这种方式清除它时,它也可以与 jQuery validate 一起使用。

-- 编辑 2013-04-09

在撰写此回复时,这是唯一的方法。通过最近的补丁,现在可以使用一种正确且更好的方法。

$remote.select2('data', null)

关于javascript - 使用 jQuery Select2 清除下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13240047/

相关文章:

javascript - 修改对象会导致修改反射(reflect)在先前推送到数组的该对象的副本中

javascript - 在 <option> 中存储 id(或其他数据)

jquery - 如何在 Bootstrap 数据表中启用排序图标?

javascript - 如果存在具有特定类的 div,则显示内容

angularjs - 带有 Ajax 功能的 Angular-UI Select2 的两种方式数据绑定(bind)

javascript - 如何在 moment.js 中格式化自定义时间?

javascript - Firebase 重新验证社交提供商

javascript - 两个模态弹出窗口;传递 id

javascript - 即使没有要显示的选项,select2 工具中的搜索框也会出现?

javascript - 制作select2的可滚动输入类型文本