How do I clear all options in a dropdown box?
Solution 1:
To remove the options of an HTML element of select
, you can utilize the remove()
method:
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for(i = L; i >= 0; i--) {
selectElement.remove(i);
}
}
// using the function:
removeOptions(document.getElementById('DropList'));
It's important to remove the options
backwards; as the remove()
method rearranges the options
collection. This way, it's guaranteed that the element to be removed still exists!
Solution 2:
If you wish to have a lightweight script, then go for jQuery. In jQuery, the solution for removing all options will be like:
$("#droplist").empty();
Solution 3:
Probably, not the cleanest solution, but it is definitely simpler than removing one-by-one:
document.getElementById("DropList").innerHTML = "";
Solution 4:
This is the best way :
function (comboBox) {
while (comboBox.options.length > 0) {
comboBox.remove(0);
}
}