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:13
while(document.getElementById("DropList").childNodes.length>0) 
{
    document.getElementById("DropList").removeChild(document.getElementById("DropList").childNodes[0]);
}
查看更多
该账号已被封号
3楼-- · 2020-01-24 07:13

For Vanilla JavaScript there is simple and elegant way to do this:

for(var o of document.querySelectorAll('#DropList > option')) {
  o.remove()
}
查看更多
我命由我不由天
4楼-- · 2020-01-24 07:14

If you wish to have a lightweight script, then go for jQuery. In jQuery, the solution for removing all options will be like:

$("#droplist").empty();
查看更多
冷血范
5楼-- · 2020-01-24 07:14

This can be used to clear options:

function clearDropDown(){
  var select = document.getElementById("DropList"),
      length = select.options.length;
  while(length--){
    select.remove(length);
  }
}
<select id="DropList" >
  <option>option_1</option>
  <option>option_2</option>
  <option>option_3</option>
  <option>option_4</option>
  <option>option_5</option>
</select>
<button onclick="clearDropDown()">clear list</button>

查看更多
虎瘦雄心在
6楼-- · 2020-01-24 07:19

If you are using JQuery and your select control has ID "DropList" you can remove its options doing this way:

$('#DropList option').remove();

Actually it works for me with any option list, like datalist.

Hope it helps.

查看更多
何必那么认真
7楼-- · 2020-01-24 07:19

Note that a select can have both
- optgroup &
- options collection
as its children.

So,

Method #1

var selectElement = document.getElementById('myselectid');
selectElement.innerHTML = '';

Method #2

var selectElement = document.getElementById('myselectid');
selectElement.textContent = '';

I tested, both work on Chrome.
I like the simpler, the old fashioned, method #1.

查看更多
登录 后发表回答