简体   繁体   中英

How to see event.target in vanila javascript in a function triggered by "oninput"

<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.

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 )

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>

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM