Adam Tong
Adam Tong

Reputation: 571

Reset programmatically the content of select2 version 4.0.1

I am using two select2 one for provinces and another for cities. My goal is to fill the cities select2 drop down by the the cities returned as json from the back-end.

For now the first call works for me the cities select2 is filled correctly. The only problem is that on the second call(triggered by province change) the content returned of json instead of replacing the content of select 2 cities it is added to it and I cannot figure out how to empty the previous content before adding.

I tried both:

$("#city").select2({'data' : null });

and

$("#city").select2('data', null );

Here is my ajax call:

$(".select2").select2();
$('#id_province').on('change', function() {
    if ($(this).val() > 0) {
        $.ajax({ 
            type: 'GET', 
            url: './cities.php', 
            data: { province: $(this).val() }, 
            dataType: 'json',
            success: function (data) { 
                console.log(data);
                $("#city").select2({'data' : null });
                $("#city").select2({
                      data: data
                }); 
            }
        });         
    }
});

And here is an example of the json returned from the server:

[{"id":"62","text":"Brandon"},{"id":"63","text":"Dauphin"},{"id":"64","text":"Flin Flon"},{"id":"65","text":"Portage la Prairie"},{"id":"66","text":"Selkirk"},{"id":"67","text":"Steinbach"},{"id":"68","text":"Thompson"},{"id":"69","text":"Winkler"},{"id":"70","text":"Winnipeg"}]

Upvotes: 0

Views: 208

Answers (1)

Sanjay Sinalkar
Sanjay Sinalkar

Reputation: 488

You can remove all options like (If your using )

$("#city").find('option').remove();

Select2 automatically updates its options list

Upvotes: 1

Related Questions