38

我在页面中有以下内容

<select name="val" size="1" >
<option value="A">Apple</option>
<option value="C">Cars</option>
<option value="H">Honda</option>
<option value="F">Fiat</option>
<option value="I">Indigo</option>                    
</select> 

如果某些条件为真,我想从我的选择中删除某些值。

例如

if(frm.product.value=="F"){
  // remove Apple and Cars from the select list
}

如何使用 javascript 执行此操作

4

19 回答 19

55

为 select 对象提供一个 id,如下所示:

<select id="mySelect" name="val" size="1" >
    <option value="A">Apple</option>
    <option value="C">Cars</option>
    <option value="H">Honda</option>
    <option value="F">Fiat</option>
    <option value="I">Indigo</option>                    
</select> 

你可以在纯 JavaScript 中做到这一点:

var selectobject = document.getElementById("mySelect");
for (var i=0; i<selectobject.length; i++) {
    if (selectobject.options[i].value == 'A')
        selectobject.remove(i);
}

But - as the other answers suggest - it's a lot easier to use jQuery or some other JS library.

于 2012-10-17T11:14:55.143 回答
13

with pure javascript

var condition = true; // your condition
if(condition) {
    var theSelect = document.getElementById('val');
    var options = theSelect.getElementsByTagName('OPTION');
    for(var i=0; i<options.length; i++) {
        if(options[i].innerHTML == 'Apple' || options[i].innerHTML == 'Cars') {
            theSelect.removeChild(options[i]);
            i--; // options have now less element, then decrease i
        }
    }
}

not tested with IE (if someone can confirm it...)

于 2012-10-17T11:18:41.353 回答
12

Check the JQuery solution here

$("#selectBox option[value='option1']").remove();
于 2014-04-11T07:44:03.333 回答
7

The index I will change as soon as it removes the 1st element. This code will remove values 52-140 from wifi channel combo box

obj = document.getElementById("id");
if (obj)
{
        var l = obj.length;
        for (var i=0; i < l; i++)
        {
            var channel = obj.options[i].value;

            if ( channel >= 52 &&  channel <= 140 )
            {
                obj.remove(i);
                i--;//after remove the length will decrease by 1 
            }
        }
    }
于 2016-03-28T08:04:14.410 回答
5

As some mentioned the length of the select element decreases when removing an option. If you just want to remove one option this is not an issue but if you intend to remove several options you could get into problems. Some suggested to decrease the index manually when removing an option. In my opinion manually decreasing an index inside a for loop is not a good idea. This is why I would suggest a slightly different for loop where we iterate through all options from behind.

var selectElement = document.getElementById("selectId");

for (var i = selectElement.length - 1; i >= 0; i--){
  if (someCondition) {
    selectElement.remove(i);
  }
}

If you want to remove all options you can do something like this.

var selectElement = document.getElementById("selectId");

while (selectElement.length > 0) {
  selectElement.remove(0);
}
于 2018-03-04T14:52:06.160 回答
4

如果您使用的是 JQuery,则如下所示:

为您的 SELECT 提供一个 ID

<select name="val" size="1" id="val">
<option value="A">Apple</option>
<option value="C">Cars</option>
<option value="H">Honda</option>
<option value="F">Fiat</option>
<option value="I">Indigo</option>                    
</select>

$("#val option[value='A'],#val option[value='C']").remove();
于 2012-10-17T11:11:56.697 回答
3

To remove options in a select by value I would do (in pure JS) :

[...document.getElementById('val').options]
    .filter(o => o.value === 'A' || o.value === 'C')
    .forEach(o => o.remove());
于 2020-04-07T13:39:21.640 回答
2

您可以使用:

if ( frm.product.value=="F" ){
    var $select_box = $('[name=val]');
    $select_box.find('[value=A],[value=C]').remove(); 
}

更新:如果你修改你的选择框有点这个

<select name="val" size="1" >
  <option id="A" value="A">Apple</option>
  <option id="C" value="C">Cars</option>
  <option id="H" value="H">Honda</option>
  <option id="F" value="F">Fiat</option>
  <option id="I" value="I">Indigo</option>                    
</select> 

非 jQuery 解决方案是这样的

if ( frm.product.value=="F" ){
    var elem = document.getElementById('A');
    elem.parentNode.removeChild(elem);
    var elem = document.getElementById('C');
    elem.parentNode.removeChild(elem);
}
于 2012-10-17T11:09:43.760 回答
2
if(frm.product.value=="F"){
    var select = document.getElementsByName('val')[0];
    select.remove(0);
    select.remove(1);
}
于 2012-10-17T11:13:17.687 回答
2

You have to go to its parent and remove it from there in javascript.

"Javascript won't let an element commit suicide, but it does permit infanticide"..:)

try this,

 var element=document.getElementsByName(val))
 element.parentNode.removeChild(element.options[0]); // to remove first option
于 2012-10-17T11:21:54.547 回答
2

This should do it

document.getElementsByName("val")[0].remove(0);
document.getElementsByName("val")[0].remove(0);

Check the fiddle here

于 2012-10-17T11:28:51.830 回答
2

Alternatively you can also accomplish this with getElementsByName

<select id="mySelect" name="val" size="1" >
<option value="A">Apple</option>
<option value="C">Cars</option>
<option value="H">Honda</option>
<option value="F">Fiat</option>
<option value="I">Indigo</option>                    
</select> 

So in matching on the option value of "C" we could remove Cars from the list.

var selectobject = document.getElementsByName('val')[0];
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == 'C' )
    selectobject.remove(i);
  }
于 2016-09-16T19:35:37.920 回答
1
document.getElementById(this).innerHTML = '';

把它放在你的 if-case 中。它所做的只是检查文档中的当前对象并将其替换为空。您将首先遍历列表,我猜您已经这样做了,因为您有那个 if。

于 2012-10-17T11:09:02.927 回答
1

For clear all options en Important en FOR : remove(0) - Important: 0

var select = document.getElementById("element_select");
var length = select.length;
for (i = 0; i < length; i++) {
     select.remove(0);
 //  or
 //  select.options[0] = null;
} 
于 2019-05-04T15:56:06.763 回答
1

The best answer is this

function f1(){
  var r=document.getElementById('ms');
  for(i=0;i<r.length;i++)
    if(r.options[i].selected==true)
    {
      r.remove(i);
      i--;
    }
}
<select id="ms" size="5" multiple="multiple">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
<option>F</option>
</select>
<input type="button" value="btn1" id="b1" onclick="f1()"/>

Because your visitor can also add custom options as he want and delete them without need any info about his options . This code is the most responsive delete code that you can write as your selected delete..

enjoy it:))))

于 2019-10-30T14:06:12.590 回答
1

A simple working solution using vanilla JavaScript:

const valuesToRemove = ["value1", "value2"];

valuesToRemove.forEach(value => {
    const mySelect = document.getElementById("my-select");

    const valueIndex = Array.from(mySelect.options).findIndex(option => option.value === value);

    if (valueIndex > 0) {
        mySelect.options.remove(valueIndex);
    }
});
于 2020-02-12T16:01:23.660 回答
1

Other way

document.querySelectorAll('#select option').forEach(i=>{
      if(frm.product.value == i.value){
         i.remove();
      }else {}
 })
于 2021-05-04T15:40:12.817 回答
0

A few caveats not covered in most answers:

  • Check against multiple items (some should be deleted, some should remain)
  • Skip the first option (-Select-) on some option lists

A take on these:

const eligibleOptions = ['800000002', '800000001'];
let optionsList = document.querySelector("select#edit-salutation");
for (let i = 1; i<optionsList.length; i++) {
    if(eligibleOptions.indexOf(optionsList.options[i].value) === -1) {
        cbxSal.remove(i);
        i--;
    }
}
于 2020-11-05T14:04:42.577 回答
-1

删除选项

$("#val option[value='A']").remove();
于 2012-10-17T11:09:32.863 回答