How can i dynamically remove all options of a drop down box in javascript?
Setting the length
to 0 is probably the best way, but you can also do this:
var mySelect = document.getElementById("select");
var len = mySelect.length;
for (var i = 0; i < len; i++) {
mySelect.remove(0);
}
Its very easy using JavaScript and DOM:
while (selectBox.firstChild)
selectBox.removeChild(selectBox.firstChild);
document.getElementById('id').options.length = 0;
or
document.getElementById('id').innerHTML = "";
The fastest solution I was able to find is the following code (taken from this article):
// Fast javascript function to clear all the options in an HTML select element
// Provide the id of the select element
// References to the old <select> object will become invalidated!
// This function returns a reference to the new select object.
function ClearOptionsFast(id)
{
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
<select id="thing"><option>fdsjl</option></select>
<script>
var el = document.getElementById('thing');
el.innerHTML = '';
// or this
while ( el.firstChild ) {
el.removeChild( el.firstChild )
}
</script>
var select = document.getElementById('yourSelectBox');
while (select.firstChild) {
select.removeChild(select.firstChild);
}