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:
xxxxxxxxxx
1
document.querySelectorAll('input').forEach(element => element.disabled = true);
In this example, we disable multiple checkbox inputs using:
document.querySelectorAll()
- to get allinput
elements,forEach()
- to iterate over the input elements and set each element'sdisable
property totrue
.
Runnable example:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="checkbox" id="option1" />
5
<input type="checkbox" id="option2" />
6
<input type="checkbox" id="option3" />
7
<button id="button1" onclick="disable()">disable</button>
8
<script>
9
function disable() {
10
document.querySelectorAll('input').forEach(element => element.disabled = true);
11
}
12
</script>
13
</body>
14
</html>
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<input type="text" id="input-1" value="Example text..." />
5
<input type="text" id="input-2" value="Example text..." />
6
<input type="text" id="input-3" value="Example text..." />
7
<button id="button1" onclick="disable()">disable</button>
8
<button id="button2" onclick="enable()">enable</button>
9
<script>
10
function disable() {
11
document.querySelectorAll('input').forEach(element => element.disabled = true);
12
}
13
14
function enable() {
15
document.querySelectorAll('input').forEach(element => element.disabled = false);
16
}
17
</script>
18
</body>
19
</html>