Sometimes, we want to remove values from select list based on condition with JavaScript.
In this article, we’ll look at how to remove values from select list based on condition with JavaScript.
Remove Values from Select List Based on Condition with JavaScript
To remove values from select list based on condition with JavaScript, we can loop through the option elements to find the element we want to remove with the for-of loop.
Then once we found the element we want to remove, then we call remove
on it to remove it.
For instance, we write:
<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>
to add the select element with some options.
Then we write:
const selectObject = document.getElementById("mySelect");
for (const o of selectObject.options) {
if (o.value === 'A') {
o.remove();
}
}
to select the select element with document.getElementById
.
Then we loop through each option element in the for-of loop.
The option elements for the select are stored in selectObject.options
.
We check if o.value
is 'A'
with the if statement.
And if it is, we call o.remove
to remove the o
option element.
Therefore, we see a drop down without the choice with text Apple in it.
Conclusion
To remove values from select list based on condition with JavaScript, we can loop through the option elements to find the element we want to remove with the for-of loop.
Then once we found the element we want to remove, then we call remove
on it to remove it.