0

How can I go about dynamically deleting an option from a drop down (select) box? The value will need to be retrieved and then deleted manually.

i.e.

    [DROP DOWN BOX]
    Apples
    Oranges
    Pears
    Kiwis
    Mangos
    Strawberries

var option_to_delete = "Pears"

Some code to dynamically search through the select box options for "Pears", and if detected, remove it.

Expected result:

    [DROP DOWN BOX]
        Apples
        Oranges
        Kiwis
        Mangos
        Strawberries

No jQuery libaries please.

Usha
  • 1,458
  • 11
  • 13
John Smith
  • 1,639
  • 11
  • 36
  • 51

3 Answers3

1

You can loop over the child nodes in the <select> and remove the child where the innerText or value that is equal to "Pears".

I have provided a jsfiddle of doing so: http://jsfiddle.net/pcb8q/

TryingToImprove
  • 7,047
  • 4
  • 30
  • 39
1

This code will loop through the dropdown box and if one of the elements is equal to your variable option_to_delete.

var dropdown = document.getElementById('ID_OF_DROPDOWN');
var option_to_delete = "Pears"

for (i=0;i<dropdown.length;  i++) {
   if (dropdown.options[i].value==option_to_delete) {
     dropdown.remove(i);
   }
}

I adapted some code from https://stackoverflow.com/a/7601791/298051

Community
  • 1
  • 1
Alex Stuckey
  • 1,250
  • 1
  • 14
  • 28
1

You can structure your html like that

    <select id="fruits">
        <option value="apples">Apple</option>
        <option value="oranges">Oranges</option>
        <option value="kiwis">Kiwis</option>
    </select>

Then in JS

    var selectBox = document.getElementById('#fruits');
    var options = selectBox.getElementsByTagName('option');
    var optionToDelete = 'apples';

    for (var i = 0; i < options.length; i++) {
        if (options[i].value === optionToDelete) {
            selectBox.removeChild(options[i]);
        }
    }
Ehtesham
  • 2,967
  • 1
  • 18
  • 20