0
if(event.keyCode === 13 ){
    return false;
  }

basically this simple code above disables a specific key, now i wanted to disable a lot of keys so i came up with something like

if(event.keyCode === 13 || event.keyCode === 14 || event.keyCode === 15 || event.keyCode === 16 , etc)

is there a faster way to do this instead of having to put a lot of ||s?

im not really sure if this has been asked before but i tried searching and couldnt find anything

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
  • 2
    Turn it on its head. Make an array of keys you want to allow and then check if the keycode is in that array. – Liftoff Jul 07 '21 at 08:40
  • [About keyCode](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode). – Teemu Jul 07 '21 at 08:49

2 Answers2

1

You can store the keyCodes in a array and check against the array with includes()

const keyCodes = [13, 14, 15, 16];

if (keyCodes.includes(event.keyCode)) {
  //do something
}
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
1

Make an array of keycode you want to disable:

const disabledKeys = [13, 14, 15, 16];

const isKeyDisabled = (keyCode) => disabledKeys.indexOf(event.keyCode) > -1

if(isKeyDisabled(event.keyCode)){
  return false;
}
Baboo
  • 4,008
  • 3
  • 18
  • 33