Disable multiple key with 1 script

50 views Asked by At

I want to disable TAB & ENTER key. I can do it in separate script like below:

<script>
document.addEventListener('keydown', function (e) {
    if (e.keyCode === 13) {
  e.preventDefault();
       e.stopPropagation();}
});
</script>

<script>
document.addEventListener('keydown', function (e) {
    if (e.keyCode === 9) {
  e.preventDefault();
       e.stopPropagation();}
});
</script>

How to combine it become just 1 script?

2

There are 2 answers

0
Sajeetharan On BEST ANSWER

Use Logical Operator OR || operator which will check for both conditions as below

<script>
document.addEventListener('keydown', function (e) {
    if (e.keyCode === 13 ||  e.keyCode === 9) {
        e.preventDefault();
       e.stopPropagation();}
});
</script>
0
Hassan Imam On

You can store all your disabled key in an array and use array#includes to check if the e.keyCode value is present in the array.

document.addEventListener('keydown', function (e) {
    const disabledKey = [13,9];
    if (disabledKey.includes(e.keyCode)){
        e.preventDefault();
    e.stopPropagation();}
});