1
<input type="text" oninput="myFunction(event)" id="i">

function myFunction(event){
    console.log(event); //can i find the keycode using this event?
}

document.getElementById('i').addEventListener("keypress", (e) => {
        console.log(e.which)});

Sorry for the beginner question guys but can I use the event in the myFunction to see the keycode press as I did by adding the event listener to the element bellow.

Bogdan
  • 659
  • 5
  • 8
  • Do you need keycode or target? – raina77ow Oct 10 '20 at 21:03
  • the target I guess. The keycode is in the target no? – Bogdan Oct 10 '20 at 21:04
  • The `target` is the element which triggered the event. – Emiel Zuurbier Oct 10 '20 at 21:04
  • if i put event.target or event.curentTarget they are both null – Bogdan Oct 10 '20 at 21:05
  • @EmielZuurbier The target is the element that triggered the event. Ok so is not possible to see there the keycode, value, etc. – Bogdan Oct 10 '20 at 21:09
  • 1
    Unlike the `keypress` event, the `input` event doesn't have data that tells which key has been pressed. It is an event that is triggered when the `value` property of the input has been changed and doesn't concern itself about keyboard input. [`keypress` is also deprecated](https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event) and should be replaced by either `keydown` or `keyup`. – Emiel Zuurbier Oct 10 '20 at 21:11
  • thanks, @EmielZuurbier for clarification – Bogdan Oct 10 '20 at 21:12

3 Answers3

0

i think that you cant get the key code in "oninput" event.. but you can do trick:

  let keyCode;
  input.addEventListener('keydown', (e) => {
    keyCode = e.keyCode
  });
  input.addEventListener('input', (e) => {
    console.log(keyCode)
  })

(from Event.keyCode doesn't work with 'on input' - undefined)

ינון רחמים
  • 566
  • 1
  • 5
  • 12
0

event.keyCode and event.which are considered to be deprecated and must not be used anymore, instead you can use event.key

Here's a working example:

<form>
    <input type="text" id="i">
</form>
  
<script>
 document.getElementById('i').addEventListener('keyup', (e) => {
    console.log(e.key); // will return exact pressed key
 });
</script>
0

You can use:

event.key

rather than event.target.


Working Example:

const showKeycode = (event) => console.log(event.key);
document.getElementById('i').addEventListener("keypress", showKeycode, false);
<input type="text" id="i">

Further Reading:

and note that event.keycode is deprecated:

Rounin
  • 27,134
  • 9
  • 83
  • 108