Remove values from select list based on condition

2020-02-10 01:29发布

I have the following in the page

<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> 

I would like to remove certain values from my select if certain conditions are true.

E.g

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

How can I do this using javascript

15条回答
Rolldiameter
2楼-- · 2020-02-10 02:03

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);
  }
查看更多
霸刀☆藐视天下
3楼-- · 2020-02-10 02:04

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
查看更多
啃猪蹄的小仙女
4楼-- · 2020-02-10 02:06

This should do it

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

Check the fiddle here

查看更多
登录 后发表回答