-1
<input type="text" id="name" onkeydown="myFunction()">

<script>
  function myFunction() {
    var name = document.getElementById("name").value;
    alert(name);
  }
</script>

when i entered "a" the system show empty, how can i get the value of KeyDown

Henry
  • 13
  • 3
  • 2
    onkeydown will trigger before the element has its value updated with the new key pressed. Maybe you should use the oninput event instead – Diego D Nov 21 '22 at 12:48
  • Did you mean the documentation which has plenty of examples? https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event – epascarello Nov 21 '22 at 12:52

1 Answers1

0

you need to define the function as follows:

<div onkeydown="myFunction(e)" />
<script>
  function myFunction(e) {
    const key = e?.key; // Should have the key you've pressed in case enter you'll find 'Enter' as string
    var name = document.getElementById("name").value;
    alert(name);
  }
</script>
Moussa Bistami
  • 929
  • 5
  • 15