wheaties
wheaties

Reputation: 35970

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?

Upvotes: 57

Views: 159462

Answers (18)

Rodrigo
Rodrigo

Reputation: 620

End of 2024, appartently the only solution that worked for me to prograatically clear Select2 (version 4.0.13) options without interfering with other events was the one hidden down in the Select2 documentation for clear select options

I used $('#mySelect2').val(null).trigger('change');

Upvotes: 0

Omid.Hanjani
Omid.Hanjani

Reputation: 1522

this code remove all results for showing new list if you need:

$('#select2Elem').data('select2').$results.children().remove()

For example, in the list of provinces and cities, when the province changes and we click on the city input, the list of old cities is still displayed until the new list is loaded.

With the code I wrote, you can delete the old list before calling ajax

Upvotes: 1

Sam San
Sam San

Reputation: 36

For Ajax, use $(".select2").val("").trigger("change"). That should solve the issue.

Upvotes: 1

Michał Szymański
Michał Szymański

Reputation: 354

This solved my problem in version 3.5.2.

$remote.empty().append(new Option()).trigger('change');

According to this issue you need an empty option inside select tag for the placeholder to show up.

Upvotes: 7

Sinan Eldem
Sinan Eldem

Reputation: 5728

This is how I do:

$('#my_input').select2('destroy').val('').select2();

Upvotes: 0

Rajdip Khavad
Rajdip Khavad

Reputation: 1

You can use this or refer further this https://select2.org/programmatic-control/add-select-clear-items

$('#mySelect2').val(null).trigger('change');

Upvotes: 0

wazza
wazza

Reputation: 101

From >4.0 in order to really clean the select2 you need to do the following:

$remote.select2.val('');
$remote.select2.html('');
selectedValues = []; // if you have some variable where you store the values
$remote.select2.trigger("change");

Please note that we select the select2 based on the initial question. In your case most probably you will select the select2 in a different way.

Hope it helps.

Upvotes: 1

ManuelSchneid3r
ManuelSchneid3r

Reputation: 16091

Since none of them all worked for me (select2 4.0.3) is went the std select way.

for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
    selectbox.remove(i);

Upvotes: 0

Andres SK
Andres SK

Reputation: 10974

I'm a little late, but this is what's working in the last version (4.0.3):

$('#select_id').val('').trigger('change');

Upvotes: 6

JackWang
JackWang

Reputation: 311

You should use this one :

   $('#remote').val(null).trigger("change");

Upvotes: 9

Vsh
Vsh

Reputation: 67

Method proposed @Lelio Faieta is working for me, but because i use bootstrap theme, it remove all bootstrap settings for select2. So I used following code:

$("#remote option").remove();

Upvotes: 6

realplay
realplay

Reputation: 2325

These both work for me to clear the dropdown:

.select2('data', null)
.select2('val', null)

But important note: value doesn't get reset, .val() will return the first option even if it's not selected. I'm using Select2 3.5.3

Upvotes: 3

Amin
Amin

Reputation: 599

For select2 version 4 easily use this:

$('#remote').empty();

After populating select element with ajax call, you may need this line of code in the success section to update the content:

  success: function(data, textStatus, jqXHR){
  $('#remote').change();
                } 

Upvotes: 30

Aegix
Aegix

Reputation: 649

I found the answer (compliments to user780178) I was looking for in this other question:

Reset select2 value and show placeholdler

$("#customers_select").select2("val", "");

Upvotes: 1

Sruit A.Suk
Sruit A.Suk

Reputation: 7263

In case of Select2 Version 4+

it has changed syntax and you need to write like this:

// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});

// clear and add new option
$("#select_with_data").html('').select2({data: [
 {id: '', text: ''},
 {id: '1', text: 'Facebook'},
 {id: '2', text: 'Youtube'},
 {id: '3', text: 'Instagram'},
 {id: '4', text: 'Pinterest'}]});

Upvotes: 48

Lelio Faieta
Lelio Faieta

Reputation: 6663

Using select2 version 4 you can use this short notation:

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

This passes a json array with null id and text to the select2 on creation but first, with .html('') empties the previously stored results.

Upvotes: 18

Maktouch
Maktouch

Reputation: 3247

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)

Upvotes: 80

Dewey
Dewey

Reputation: 1223

This is the proper one, select2 will clear the selected value and show the placeholder back .

$remote.select2('data', null)

Upvotes: 32

Related Questions