Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

javascript - Clear dropdown using jQuery Select2

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:

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works for me:

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

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

-- 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...