How to remove all options from a dropdown using jQuery / JavaScript
Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-
var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}
You can either use .remove() on option elements:
.remove() : Remove the set of matched elements from the DOM.
$('#models option').remove(); or $('#models').remove('option');
or use .empty() on select:
.empty() : Remove all child nodes of the set of matched elements from the DOM.
$('#models').empty();
however to repopulate deleted options, you need to store the option while deleting.
You can also achieve the same using show/hide:
$("#models option").hide();
and later on to show them:
$("#models option").show();
You didn't say on which event.Just use below on your event listener.Or in your page load
$('#models').empty()
Then to repopulate
$.getJSON('@Url.Action("YourAction","YourController")',function(data){
var dropdown=$('#models');
dropdown.empty();
$.each(data, function (index, item) {
dropdown.append(
$('<option>', {
value: item.valueField,
text: item.DisplayField
}, '</option>'))
}
)});