I have the following in the page
document.getElementById(this).innerHTML = '';
Put it inside your if-case. What it does is just to check for the current object within the document and replace it with nothing. You'll have too loop through the list first, I am guessing you are already doing that since you have that if.
if(frm.product.value=="F"){
var select = document.getElementsByName('val')[0];
select.remove(0);
select.remove(1);
}
To remove options in a select by value I would do (in pure JS) :
[...document.getElementById('val').options]
.filter(o => o.value === 'A' || o.value === 'C')
.forEach(o => o.remove());
A few caveats not covered in most answers:
A take on these:
const eligibleOptions = ['800000002', '800000001'];
let optionsList = document.querySelector("select#edit-salutation");
for (let i = 1; i<optionsList.length; i++) {
if(eligibleOptions.indexOf(optionsList.options[i].value) === -1) {
cbxSal.remove(i);
i--;
}
}
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...)
As some mentioned the length of the select element decreases when removing an option. If you just want to remove one option this is not an issue but if you intend to remove several options you could get into problems. Some suggested to decrease the index manually when removing an option. In my opinion manually decreasing an index inside a for loop is not a good idea. This is why I would suggest a slightly different for loop where we iterate through all options from behind.
var selectElement = document.getElementById("selectId");
for (var i = selectElement.length - 1; i >= 0; i--){
if (someCondition) {
selectElement.remove(i);
}
}
If you want to remove all options you can do something like this.
var selectElement = document.getElementById("selectId");
while (selectElement.length > 0) {
selectElement.remove(0);
}