I have the following dropdown list:
var selectbox = document.getElementById('DD1');
for(var i = 0; i < selectbox.options.length; i++)
{
if(selectbox.options[i].value == 'D')
selectbox.remove(i);
}
Since everyone else has proposed basically the same solution, here's a simpler solution if you have the benefit of only targeting modern browsers:
var el = document.querySelector('select[name=DD1] option[value=D]');
el.parentNode.removeChild(el);
Or, for every browser:
var el;
if(typeof document.querySelector == 'function') {
el = document.querySelector('select[name=DD1] option[value=D]');
} else {
for(var child in document.getElementById('DD1').childNodes) {
if(child.textContent == 'D') {
el = child;
break;
}
}
}
el && el.parentNode.removeChild(el);
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/
There's probably a little cleaner way to do this but I am rusty with javascript.
var options = documentgetElementsByTagName("option");
for(i=0; i<options.length; i++)
{
if(options[i].value == "D")
{
this.class += "displayNone";
}
}
.displayNone{ display: none; }
this is not tested so I don't know if it would work.
var select=document.getElementById('DD1');
for (i=0;i<select.length; i++) {
if (select.options[i].value=='D') {
select.remove(i);
}
}
Try looping over the options, checking the value, and if it matches, set it to null:
function removeByValue(id, value) {
var select = document.getElementById(id);
for (var i=0, length = select.options.length; i< length; i++) {
if (select.options[i] && select.options[i].value === value) {
select.options[i] = null;
}
}
}
removeByValue('DD1', 'D');