Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript clear content of selectbox

Tags:

javascript

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?

like image 872
user197483 Avatar asked Nov 26 '12 15:11

user197483


3 Answers

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.

like image 193
Denys Séguret Avatar answered Sep 28 '22 08:09

Denys Séguret


var selectbox = document.getElementById(selectbox);

document.getElementById("emptyBox").innerHTML = selectbox.innerHTML;
selectbox.innerHTML = "";
like image 23
Matt Avatar answered Sep 28 '22 08:09

Matt


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"));
like image 27
Metro Smurf Avatar answered Sep 28 '22 07:09

Metro Smurf