0

I am looping over select drop down options and want to remove an option if its value meets certain specified condition. I used selectObject.removechild(option)/option.remove(), but in doing so only one option that meets the condition first removes but not others because at each deletion operation the size of the list reduces and hence all options not get traversed. I want pure JavaScript solution (no JQuery). I searched much and only found JQuery solutions. Is there any other way?

var selectObject = document.getElementById("sel");
var opts = selectObject.options;
for(var i = 0; opts.length; i++){
  if(opts[i].value == val){
    opts[i].remove();
    //i also tried with: selectObject.removeChild(opts[i])
  }
}
Abdullah Danyal
  • 1,106
  • 1
  • 9
  • 25
  • 2
    Show us your code and example html. See [mcve] , and [ask] – charlietfl Apr 25 '17 at 17:42
  • Possible duplicate of [Remove values from select list based on condition](http://stackoverflow.com/questions/12932959/remove-values-from-select-list-based-on-condition) – Mils Apr 25 '17 at 17:45

2 Answers2

0

Using a for...of loop instead of an index, I was able to get the code to work. Here is a codepen showing it working.

var selectObject = document.getElementById("sel");
var opts = selectObject.options;
for(let opt of opts){
  if(opt.value == val){
    opt.remove();
    //i also tried with: selectObject.removeChild(opts[i])
  }
}
Jacob Petersen
  • 1,463
  • 1
  • 9
  • 17
0

var empty = function() {
    s = document.getElementById('s');
    for (var i = 0; i < s.children.length; i++) {
      o = s.children[i];
      if (o.value == 2) {
        s.removeChild(o);
        i--
      }
    }
    }
<select id='s'>
 <option>1</option>
 <option>1</option>
 <option>2</option>
 <option>1</option>
 <option>1</option>
 <option>1</option>
 <option>1</option>
 <option>2</option>
 <option>1</option>
 <option>1</option>
 <option>1</option>
<select>

<button onclick = 'empty()'>empty</button>
Rhea
  • 644
  • 1
  • 5
  • 14