Remove values from select list based on condition
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
}
}
}
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...)
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.
Check the JQuery solution here
$("#selectBox option[value='option1']").remove();