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 07:08

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();});
查看更多
▲ chillily
3楼-- · 2020-01-24 07:11

This is the best way :

function (comboBox) {
    while (comboBox.options.length > 0) {                
        comboBox.remove(0);
    }        
}
查看更多
祖国的老花朵
4楼-- · 2020-01-24 07:11

with PrototypeJS :

$('yourSelect').select('option').invoke('remove');
查看更多
smile是对你的礼貌
5楼-- · 2020-01-24 07:11

I think that is the best sol. is

 $("#myselectid").html(''); 

查看更多
forever°为你锁心
6楼-- · 2020-01-24 07:11
var select = document.getElementById('/*id attribute of your select here*/');
for (var option in select){
    select.remove(option);
}
查看更多
仙女界的扛把子
7楼-- · 2020-01-24 07:12

This is a bit modern and pure JavaScript

document.querySelectorAll('#selectId option').forEach(option => option.remove())

查看更多
登录 后发表回答