views:

38

answers:

4

I'm stumped.
My code works in IE but breaks in Safari, Firefox, and Opera. (big surprise)

document.getElementById("DropList").options.length=0;

After searching, I've learned that it's the "length=0" that it doesn't like.
I've tried "...options=null" and "var clear=0; ...length=clear" with the same result.

I am doing this to multiple objects at a time, so I am looking for some lightweight JS code.

+3  A: 

You can loop through and remove them like this:

var select = document.getElementById("DropList");
for (i = 0; i < select.options.length; i++) {
  select.options[i] = null;
}

The jQuery version, if it's an option (wasn't in your tags):

$("#DropList").empty();
Nick Craver
It still crashed when i try the above JS...probably some other conflicting code.I hadn't considered jQuery. I think that's just what I'm looking for...but maybe to remove the whole option child: $("select[id$=DropList] > option").remove();
Kirt
A: 

To remove the options of a select html object, you can use this piece of code:

function removeOptions(selectbox)
{
    var i;
    for(i=selectbox.options.length-1;i>=0;i--)
    {
        selectbox.remove(i);
    }
}
//using the function:
removeOptions(document.getElementById("mySelectObject"));

This will work in all browsers. =)

Fabiano
+1  A: 

Try

document.getElementsByTagName("Option").length=0

Or maybe look into the removeChild() function.

Or if you use jQuery framework.

$("DropList Option").each(function(){$(this).remove();});
Razor Storm
A: 

If you wish to have a lighweight scrip, go for jQuery. In jQuery, the solution for removing all options will be like: $("#droplist").empty();

Kangkan