Clear dropdown using jQuery Select2
Asked Answered
A

17

57

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?

Allegorical answered 5/11, 2012 at 20:43 Comment(5)
did you try to find the element and then doing .remove()?Yalonda
@EH_warch I don't want to remove the Select2 itself, merely clear the value that has been set.Allegorical
i ment not to remove the whole select2, but the element. Perhaps something like $('.itemSelected').remove()? or you mean like doing $remote.empty()?Yalonda
@EH_warch will that remove the value itself, or just the displayed element. There's two concerns here, one is making sure it appears as if we haven't selected a value and then making sure the value isn't set. I am not sure if doing what you suggest won't cause an issue with the library or fix the problem. Will it?Allegorical
Asking JS questions without a fiddle is not a path to happiness. People have to do way too much grunt work to help you.Catamaran
O
79

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)
Onomastics answered 22/11, 2012 at 20:24 Comment(4)
While this clears the selection, I'd like to show the placeholder again.Cortege
@SimonHürlimann This would be nice. I stored the placeholder text in memory and then set the text using this solution. You might also want to add the 'select2-default' class to the 'select2-choice' element to get the proper styling.Enamel
is not working for me. the cross button is not coming though i've selected allowClear: true.Wallow
@soham.m17 The clear button only appears after you select a value again. @ Aktee awesome solution, tested with regular select2, multiple and ajax source multiple select and it works fine in all of these modes, even the placeholder is put back. All of this tested with Select2 3.3.2Activate
C
47

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'}]});
Caracul answered 10/5, 2015 at 9:26 Comment(4)
You are my hero! thank you, this fixed version 4.0 not resetting with select2('data', null);Redden
that's the only way to you clean your select without fire change event.Benoni
Tried many other solution in other reply, only yours work for me on version 4.0.6-rc.0Raab
thanks dude, you saved my life. i wasted a lot of hours for this problem.Edda
J
32

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

$remote.select2('data', null)
Jon answered 16/2, 2013 at 19:16 Comment(1)
Again, 4.0+ broke a lot of things! this for instance!!Redden
C
29

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();
                } 
Calotte answered 16/11, 2015 at 7:19 Comment(3)
This is using the jQuery empty function to remove all child objects, which may have un-intended consequences.Z
Please explain more, which consequences? This works for me every time I use it.Calotte
It does work to an extent, but it removes all child elements from the DOM element you're selecting. Select2 relies on specific DOM elements that it builds to give you the additional functionality / behavior. So just warning that this is not a Select2 mechanism for resetting, instead you are manipulating the DOM after Select2 has initialized the element, so it may lead to loss of functionality. I found the best answer for this question @ #17957540.Z
E
18

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.

Enceinte answered 20/8, 2015 at 10:28 Comment(5)
This is working perfectly. In select2 version 4 , $remote.select2('data', null) is not working.Kimmie
Works perfectly with select2 4.0.2.Duma
@AbdulHameed Do you have an empty <option> in your html?Enceinte
@LelioFaieta no i just fetching the values from server and have a placeholder in htmlHah
i dont' know but that worked $('#id').select2('val', 'placeholder') ThanksHah
U
8

You should use this one :

   $('#remote').val(null).trigger("change");
Utham answered 5/8, 2016 at 8:8 Comment(1)
This is the correct solution from now on according to deprecated message thrown in debug mode: "The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead"Immuno
T
7

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.

Trapeziform answered 29/1, 2019 at 15:14 Comment(0)
S
6

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();
Shrader answered 16/6, 2016 at 15:33 Comment(0)
P
6

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

$('#select_id').val('').trigger('change');
Pontus answered 17/8, 2016 at 14:31 Comment(0)
P
3

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

Penance answered 22/1, 2016 at 0:15 Comment(0)
Z
1

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", "");
Z answered 21/12, 2015 at 21:58 Comment(1)
Please let me know if I should do something different to link a different SO question.... New to this :-)Z
P
1

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.

Pachysandra answered 15/6, 2017 at 12:21 Comment(0)
D
1

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

Dramatic answered 28/12, 2020 at 19:32 Comment(2)
Welcome to SO. Though we thank you for your answer, it would be better if it provided additional value on top of the other answers. In this case, your answer does not provide additional value, since Rajdip Khavad already posted that solution. If a previous answer was helpful to you, you should vote it up once you have enough reputation.Colston
Not sure about the above comment, this was great help for me and very clear.Locomotive
A
1

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

Amoebic answered 24/5, 2021 at 10:53 Comment(0)
R
0

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);
Radiothermy answered 19/5, 2017 at 8:9 Comment(0)
B
0

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

$('#mySelect2').val(null).trigger('change');
Bursary answered 4/4, 2018 at 4:52 Comment(0)
M
0

This is how I do:

$('#my_input').select2('destroy').val('').select2();
Mehta answered 4/4, 2018 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.