Reputation: 18346
I have 2 select2 component in my project. Values of one of them is depended on value of other one which is selected. Here is the code:
$('#states').on('change', function() {
$.get({
url: 'https://mydomain/cities.php/?sid='+$(this).val(),
dataType: 'json',
success: function(response) {
citiesData = new Array();
$.each(response, function(index, el) {
citiesData.push({'id' : el.id, 'text' : el.title});
});
$('#cities').select2({data:citiesData});
}
});
});
Problem is select2 which shows cities doesn't get empty for each change of states and cities of selected state is added to pre-selected state.
How can I empty select2 of cities before inserting new data?
Upvotes: 1
Views: 331
Reputation: 632
Try this in your ajax success function.
$('#cities').select2().val();
And to empty the select2
$("#cities").empty();
Upvotes: 4