I have the following in the page
<select 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>
I would like to remove certain values from my select if certain conditions are true.
E.g
if(frm.product.value=="F"){
// remove Apple and Cars from the select list
}
How can I do this using javascript
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
For clear all options en Important en FOR : remove(0) - Important: 0
Check the JQuery solution here
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.
If you want to remove all options you can do something like this.
Give an id for the select object like this:
You can do it in pure JavaScript:
But - as the other answers suggest - it's a lot easier to use jQuery or some other JS library.