Languages
[Edit]
EN

JavaScript - disable multiple inputs on click

0 points
Created by:
trincot
330

In this article, we would like to show you how to disable multiple inputs on click using JavaScript.

Quick solution:

document.querySelectorAll('input').forEach(element => element.disabled = true);

 

Practical example

In this example, we disable multiple checkbox inputs using:

  • document.querySelectorAll() - to get all input elements,
  • forEach() - to iterate over the input elements and set each element's disable property to true.

Runnable example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <input type="checkbox" id="option1" />
  <input type="checkbox" id="option2" />
  <input type="checkbox" id="option3" />
  <button  id="button1" onclick="disable()">disable</button>
  <script>
    function disable() {
      document.querySelectorAll('input').forEach(element => element.disabled = true);
    }
  </script>
</body>
</html>

2. Disable / enable buttons with text inputs

In this example, we use the same method as above to disable text type inputs. Additionally, we create a new button that can enable them again.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <input type="text" id="input-1" value="Example text..." />
  <input type="text" id="input-2" value="Example text..." />
  <input type="text" id="input-3" value="Example text..." />
  <button id="button1" onclick="disable()">disable</button>
  <button id="button2" onclick="enable()">enable</button>
  <script>
    function disable() {
      document.querySelectorAll('input').forEach(element => element.disabled = true);
    }

    function enable() {
      document.querySelectorAll('input').forEach(element => element.disabled = false);
    }
  </script>
</body>
</html>

References

  1. Document.querySelector() - Web APIs | MDN
  2. HTMLSelectElement.disabled - Web APIs | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join