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?
You 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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With