Clear dropdown using jQuery Select2

javascript, jquery, jquery-select2

Solution

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)

Problem

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?

Original source

Related problems