As part of my populating selectbox function I am clearing the contents of the populated select box and then inserting options to a empty box. Although the select box is not being cleared correctly and a lot of options are not removed. I am using the following code to clear the contents of the select box:
for(var i = 0; i < document.getElementById(selectbox).options.length; i++)
document.getElementById(selectbox).options[i] = null;
Why not all the options are removed from the selectbox?
As part of my populating selectbox function I am clearing the contents of the populated select box and then inserting options to a empty box. Although the select box is not being cleared correctly and a lot of options are not removed. I am using the following code to clear the contents of the select box:
for(var i = 0; i < document.getElementById(selectbox).options.length; i++)
document.getElementById(selectbox).options[i] = null;
Why not all the options are removed from the selectbox?
Share Improve this question asked Nov 26, 2012 at 15:43 user197483user197483 3042 gold badges3 silver badges11 bronze badges 6 | Show 1 more comment4 Answers
Reset to default 15You can simply do
document.getElementById(selectbox).options.length = 0;
You could also have removed the elements one by one, almost like you did, but you must take into account the fact the length of options
changes when you iterate. The correct way to remove while iterating would have been
for (var i=document.getElementById(selectbox).options.length; i-->0;)
document.getElementById(selectbox).options[i] = null;
But the first solution is simpler of course.
var selectbox = document.getElementById(selectbox);
document.getElementById("emptyBox").innerHTML = selectbox.innerHTML;
selectbox.innerHTML = "";
As an alternative and more terse method of clearing all options of a select list, we can take advantage of JavaScript's falsey value of zero and then simply remove the option from the Dom:
function clearSelectList(list) {
// when length is 0, the evaluation will return false.
while (list.options.length) {
// continue to remove the first option until no options remain.
list.remove(0);
}
}
Usage would then be:
var list = document.getElementById("selectbox");
clearSelectList(list);
Or more succinctly:
clearSelectList(document.getElementById("selectbox"));
this example with new generation JavaScript. I do recommend to use.
[...cbrCenterSelectbox.options].forEach(option => option.remove())
document.getElementByID(selectbox.options.length
is changing as you remove elements from it. I do not know this for sure as I am far from Javascript pro though. – thatidiotguy Commented Nov 26, 2012 at 15:46