使用jQuery Select2清除下拉列表 [英] Clear dropdown using jQuery Select2

查看:1377
本文介绍了使用jQuery Select2清除下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用精彩的 Select2 库以编程方式清除下拉列表。使用Select2 查询选项,使用远程ajax调用动态填充下拉列表。

I'm trying to programmatically clear a drop down using the fantastic Select2 library. The drop down is dynamically filled with a remote ajax call using the Select2 query option.

HTML:

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

Javascript:

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',' ')抛出以下异常:

Unfortunately, the call to $remove.select2('val', '') throws the following exception:

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

我已尝试设置 attr ,设置 val text 和Select2特定数据功能。似乎无法使这个家伙清楚地工作在一个单选按钮的方式。有人有建议吗?

I've tried setting the attr, setting the val, text and the Select2 specific data function. Can't seem to make the guy clear and work in a radio button like manner. Anyone got suggestions?

推荐答案

这对我有用:

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

当你清除它时,它也适用于jQuery验证。

It also works with jQuery validate when you clear it that way.

-
edit 2013-04-09

-- edit 2013-04-09

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

At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.

$remote.select2('data', null)

这篇关于使用jQuery Select2清除下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆