tags:

views:

140

answers:

6

Is there a Javascript Clear function for a dropdownlist per say.

ddlist.Clear(); or something of that sort?

A: 

For an array, you can just use

arr = [];

for elements, etc, you'll need to use a framework or delete each element in a loop

valya
+5  A: 

no, there isn't. but you could do so like this:

function clearDropDownList(ddl) {
    while (ddl.hasChildNodes()) {
        ddl.removeChild(ddl.lastChild);
    }
}
ob
this did not work..
CoffeeAddict
+6  A: 

I'd recommend checking out jQuery, it has some functionality similar to what you're looking for and can help javascript development in general be easier and behave closer to the same on multiple browsers.

http://docs.jquery.com/Manipulation/empty

Bryan McLemore
+1  A: 

You can set the innerHTML to "", or remove all the option childs programmatically:

var element = document.getElementById("selectId");
element.innerHTML = "";

Or:

var element = document.getElementById("selectId");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}
CMS
+1 for conciseness.
cballou
+5  A: 

If by "clear the values" you mean remove all the dropdown <option> elements, the quickest and most concise way is:

ddlist.options.length = 0
Roatin Marth
beautiful answer
John K
This correct. No loops required!
Diodeus
nice! very clean
CoffeeAddict
A: 

Short.

while (ddlist.options.length) 
     ddlist.options.remove(0);
John K