user197483 user197483 - 3 months ago 19
Javascript Question

Javascript clear content of 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?

Answer

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.