0

I want to track user key presses in input field in a separate function and call a function based on onkeydown value. What I have below just doesn't work. Nothing happens. I'm open to eye-opening revelations and commentary. I think I'm missing something major.

function find_key(Fval, Fid) {

  //prevents malicious characters
  if ((event.charCode <= 47) || (event.charCode >= 64)) {
    return;
  };

  // user presses ctrl + delete
  // this doesn't work, nothing happens
  if (event.code == 46 && (event.ctrlKey || event.metaKey)) {
    alert('Undo!');
  }

  // user presses ctrl + enter 
  // this doesn't work, nothing happens
  if (event.ctrlKey && e.keyCode == 13) {
    alert("grab");
    grabName(Fval, Fid);
  }

}
<input onkeydown="find_key(this,this.id);" id="P${i}" />

I tried this based on a suggestion: (it doesn't work, though)

`<input class = 'tiger' id = "P${i}"  />`;

document.getElementsByClassName('tiger').addEventListener('keypress', findKey);

function find_key (e) {

if (event.code == 46 && (event.ctrlKey || event.metaKey)) 
{ alert('Undo!'); }
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
verlager
  • 794
  • 5
  • 25
  • 43
  • This code doesn't do a lot of things. Too much to give a proper answer. In the line that "doesn't work", you're using `e.` instead of `event.`. That won't work. Also, you need to detect the `keyCode == 13` before you return from the function, because the `charCode` of `keyCode == 13` is zero. So put the "user presses ctrl + enter" line first. – KIKO Software Jun 26 '22 at 09:11
  • Bro, I guess you're unable to detect if multiple keys are pressed at once, possible duplicate post can be found [here](https://stackoverflow.com/questions/5203407/how-to-detect-if-multiple-keys-are-pressed-at-once-using-javascript). – Piyush Pranjal Jun 26 '22 at 09:11

1 Answers1

0

You need to pass event as an argument (please note exact argument name "event" must be used).

<input onkeydown = "find_key(event, this, this.id);" id = "P${i}"  />;

And then in js

function find_key (event, Fval, Fid) {
    //...
}

P.S. why not using document method in js code and adding event listener to your input directly?

document.getElementById('input_el_id').addEventListener('keydown', findKey);

function findKey(e) {
    //...
}
Andyally
  • 863
  • 1
  • 9
  • 22
  • Because I may have 48 input field with different ID's (#P1, #P2, .... – verlager Jun 26 '22 at 09:58
  • In that case it is even more preferred to use JS and render inputs dynamically by iterating through your id's or other input related data and appending each input to your parent node as a child while attaching id attribute and event listeners dynamically. It ensures you won't need to type each input manually in your html code. – Andyally Jun 26 '22 at 10:04