Suyash Gupta
Suyash Gupta

Reputation: 576

keypress with backspace and delete

I'm sure all the web developers have encountered a scenario where they needed to check the press of all the characters keys along with backspace & delete.

For instance, To display an error message as soon as user enters some invalid key. For this, I would continuously listen to some key event to check for the invalid key.

Since, keypress doesn't work for backspace and delete keys, we use keydown event. But, the problem with keydown event is it would fire the event on all keys including Alt, Ctrl, Tab, etc., the keys for which I don't need to execute the logic for finding out the invalid keys.

The common workaround to this we use and see is we filter out the non-required keys by checking the keycode.

So, I wanted to know if there was some other way as in some other key event in order to not list down all the non-required keys in the above scenario?

Upvotes: 2

Views: 10354

Answers (2)

Pramod Kharade
Pramod Kharade

Reputation: 2085

Already Answer has been given so there is no much change in it.

Instead of check the key with their name. I have checked with KeyCode because some time/case browser return the event.key as empty so in-order to prevent the case we can go with keyCode.

You can register the event by addEventListener with keyPress or KeyDown and check the Keycode of Delete or space bar and return if condition get matched find the link for all key code : KeyCodes List

 addEventListener('keydown', (event) => {
      // Check for allowed keys on keydown with Code
      if (event.keyCode === 32 || event.keyCode === 46) {
        console.log("Invalid key:",event.code);
        return;
      }
    });

Hope, it will solve your problem some extend.

Upvotes: 0

FAISAL
FAISAL

Reputation: 34673

You can register two separate event listeners e.g. (keydown) for Delete & Backspace and (keypress) for everything else in your component's initialization as shown below:

  ngOnInit() {

    addEventListener('keypress', (event: KeyboardEvent) => {
      // Execute your logic here.
        console.log(event);
    });

    addEventListener('keydown', (event: KeyboardEvent) => {
      // Check for allowed keys on keydown
      if (event.key === 'Delete' || event.key === 'Backspace') {
        // Execute your logic here.
        console.log(event);
      }
    });

  }

Upvotes: 4

Related Questions