EN
JavaScript - disable multiple inputs on click
0
points
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 allinputelements,forEach()- to iterate over the input elements and set each element'sdisableproperty totrue.
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>