Categories
JavaScript Answers

How to enable or disable input elements with JavaScript?

Spread the love

Sometimes, we want to enable or disable input elements with JavaScript.

In this article, we’ll look at how to enable or disable input elements with JavaScript.

How to enable or disable input elements with JavaScript?

To enable or disable input elements with JavaScript, we can loop through the inputs to disable the ones we want.

For instance, we write:

<button>
  toggle
</button>
<input>
<input>
<input>

to add a button with inputs.

Then we write:

const toggleInputs = () => {
  const inputs = document.getElementsByTagName('input');
  for (const input of inputs) {
    input.disabled = !input.disabled;
  }
}

document.querySelector('button').onclick = toggleInputs;

We define the toggleInputs function to select the inputs with getElementsByTagName.

Then we loop through the inputs with a for-of loop.

In the loop body, we toggle the disabled property of each input to toggle disabling them.

Therefore, when we click toggle, we see all the inputs being toggled between enabled and disabled.

Conclusion

To enable or disable input elements with JavaScript, we can loop through the inputs to disable the ones we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *