How to remove all options from a dropdown using jQuery / JavaScript
Solution 1
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>'))
}
)});
Solution 2
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();
Solution 3
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);}
TotalNewbie
Updated on July 19, 2022Comments
-
TotalNewbie almost 2 years
I have a dropdown as seen below:
<select id="models" onchange="removeElements()"> <option id = "remove" value="0">R8</option> <option id = "remove" value="1">Quattro</option> <option id = "remove" value="2">A6 hatchback</option> </select>
How would I create the script
removeElements()
that would remove all of the options within the select?