How do I clear all options in a dropdown box?

2020-01-24 06:44发布

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.

27条回答
再贱就再见
2楼-- · 2020-01-24 06:56

The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null, as that may cause unexpected behaviour.

var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
    select.remove(i);

Or if you prefer, you can make it a function:

function clearOptions(id)
{
    var select = document.getElementById(id);
    for (var i = select.options.length - 1 ; i >= 0 ; i--)
        select.remove(i);
}
clearOptions("myselect");
查看更多
倾城 Initia
3楼-- · 2020-01-24 06:59

You can use the following to clear all the elements. Note that

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
  select.options[i] = null;
}
查看更多
够拽才男人
4楼-- · 2020-01-24 06:59

This is the shortest way:

document.getElementById('mySelect').innerText = null

One line, no for, no JQuery, simple.

查看更多
我命由我不由天
5楼-- · 2020-01-24 07:00

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. =)

查看更多
Ridiculous、
6楼-- · 2020-01-24 07:00
function removeOptions(obj) {
    while (obj.options.length) {
        obj.remove(0);
    }
}
查看更多
7楼-- · 2020-01-24 07:01
var select =$('#selectbox').val();
查看更多
登录 后发表回答