45

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

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Jacob
  • 14,463
  • 65
  • 207
  • 320

20 Answers20

62

Give an id for the select object like this:

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

You can do it in pure 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.

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
Andrew
  • 899
  • 8
  • 9
14

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

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
  • You don't need to call `theSelect.getElementsByTagName('OPTION')`, you can use `theSelect.options` instead. – Emaborsa Dec 05 '17 at 13:02
14

Check the JQuery solution here

$("#selectBox option[value='option1']").remove();
Community
  • 1
  • 1
Dumisani
  • 2,988
  • 1
  • 29
  • 40
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 
            }
        }
    }
Amit Shah
  • 7,771
  • 5
  • 39
  • 55
7

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);
}
Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
Jason Saruulo
  • 1,837
  • 4
  • 21
  • 21
6

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());
Luc Wanlin
  • 97
  • 2
  • 5
  • To remove one option: `[...document.getElementById('val').options].filter(o => o.value === 'F')[0].remove();` – kiatng Dec 24 '20 at 02:26
4

If you are using JQuery, it goes as follows:

Give an ID to your SELECT

<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();
Filipe Melo
  • 558
  • 5
  • 10
3

This should do it

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

Check the fiddle here

Jacob George
  • 2,559
  • 1
  • 16
  • 28
  • this builds a hard dep on the ordering of the dom. at some point this will bite you in the ass. – denov Nov 13 '20 at 20:25
2

You may use:

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

Update: If you modify your select box a bit to this

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

the non-jQuery solution would be this

if ( frm.product.value=="F" ){
    var elem = document.getElementById('A');
    elem.parentNode.removeChild(elem);
    var elem = document.getElementById('C');
    elem.parentNode.removeChild(elem);
}
Thariama
  • 50,002
  • 13
  • 138
  • 166
2
if(frm.product.value=="F"){
    var select = document.getElementsByName('val')[0];
    select.remove(0);
    select.remove(1);
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117
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
bipen
  • 36,319
  • 9
  • 49
  • 62
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);
  }
2

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;
} 
2

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

1
document.getElementById(this).innerHTML = '';

Put it inside your if-case. What it does is just to check for the current object within the document and replace it with nothing. You'll have too loop through the list first, I am guessing you are already doing that since you have that if.

Ms01
  • 4,420
  • 9
  • 48
  • 80
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);
    }
});
ettanany
  • 19,038
  • 9
  • 47
  • 63
1

Other way

document.querySelectorAll('#select option').forEach(i=>{
      if(frm.product.value == i.value){
         i.remove();
      }else {}
 })
German Gracia
  • 351
  • 4
  • 8
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--;
    }
}
MichaelF
  • 3
  • 3
0

Use HTML5 Native API for Select. Fetch the options and pass the index in the remove function.

var s = document.getElementById("ctl00_ContentPlaceHolder1_ddlxml")
var options = s.options
for(var i=0; i<options.length; i++) {
    if(options[i].text==='UP3151005_180822FTO_1055352') s.remove(i);
    if(options[i].text==='UP3151005_180822FTO_1055371') s.remove(i);
    if(options[i].text==='UP3151005_180822FTO_1055560') s.remove(i);
    if(options[i].text==='UP3151005_180822FTO_1055617') s.remove(i);
}
Sorter
  • 9,704
  • 6
  • 64
  • 74
-1

Removing an option

$("#val option[value='A']").remove();
Udan
  • 5,429
  • 2
  • 28
  • 34