Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from dropdown list on page load (no jquery)

I have the following dropdown list:

<select name="DD1" id="DD1">
    <option value="B">B</option>
    <option value="D">D</option>
    <option value="E">E</option>
    <option value="F">F</option>
    <option value="R">R</option>
</select>

On page load I need to hide/delete option D. I can't go by the index because that list is dynamic so I have to use the value parameter or the actual text that gets rendered.

I've tried finding the answer but all the solutions I came across use JQuery for this and I don't have the option to do this.

Anyone have a way to hide option D just using Javascipt on page load so the user never sees that option?

Thanks

like image 989
markiyanm Avatar asked Dec 02 '22 01:12

markiyanm


2 Answers

var select=document.getElementById('DD1');

for (i=0;i<select.length;  i++) {
   if (select.options[i].value=='D') {
     select.remove(i);
   }
}
like image 87
VirtualTroll Avatar answered Dec 17 '22 17:12

VirtualTroll


I used window.addEventListener it won't work on down-level browsers that don't support it. I suggest creating your own addEvent method that abstracts the inconsistencies - if jQuery (or some other framework) is not allowed.

window.addEventListener("load", function(){
   var list = document.getElementById('DD1'), el;

   for(var i in list.children){
       el = list.children[i];
       if(el.hasOwnProperty('value')) {
          if(el.value == 'D') {
             el.style.display = 'none';
             break;
          }
       }
   }
}, false);

http://jsfiddle.net/UV6nm/2/

like image 43
Alex Avatar answered Dec 17 '22 19:12

Alex