How to disable an option in a select based on its value with JavaScript?

Sometimes, we want to disable an option in a select based on its value with JavaScript.

In this article, we’ll look at how to disable an option in a select based on its value with JavaScript.

How to disable an option in a select based on its value with JavaScript?

To disable an option in a select based on its value with JavaScript, we can set its disabled property to true.

For instance, we write

document.querySelectorAll("#foo option").forEach((opt) => {
  if (opt.value === "example") {
    opt.disabled = true;
  }
});

to select the option elements in the drop down with querySelector.

Then we call forEach with a callback that checks if the value attribute’s value is 'example'.

If it is, then we set its disabled property to true to disable it.

Conclusion

To disable an option in a select based on its value with JavaScript, we can set its disabled property to true.