How to remove values from select list based on condition with JavaScript?

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.

How to remove values from select list based on condition with JavaScript?

To remove values from select list based on condition with JavaScript, we can watch the selected value of the drop down.

Then we can remove the values accordingly.

For instance, we write:

<select>
  <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 a select drop down.

Then we write:

const select = document.querySelector("select");

select.addEventListener('change', () => {
  if (select.value === 'F') {
    const aIndex = [...select.options].findIndex(o => o.value === 'A')
    select.options.remove(aIndex);
    const cIndex = [...select.options].findIndex(o => o.value === 'C')
    select.options.remove(cIndex);
  }
})

We get the select element with document.querySelector.

Then we add a change event listener with addEventListener.

In the event listener, we check if select.value if 'F'.

If it is, then we get the ones that we want to remove by spreading the options into an array.

Then we call findIndex with a function that checks the value of the option to look for the index of the ones we want to remove.

Then we call select.options.remove to remove them.

Now when we select Fiat, we see that the Apple and Cars options are removed.

Conclusion

To remove values from select list based on condition with JavaScript, we can watch the selected value of the drop down.

Then we can remove the values accordingly.