17
function h(x)
{
    alert(x);
}

<input onkeypress=h(this.value) type=text>

When I press 'a' alert empty
When I press 'b' after 'a' =>ab alert only 'a' and I want 'ab'
When I type 'abcd' it alert 'abc' only and I want 'abcd'

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Wasim A.
  • 9,660
  • 22
  • 90
  • 120

3 Answers3

26

your event fires before letter is registered. you should use onkeyup event. It kicks-in after you release key

Lixas
  • 6,938
  • 2
  • 25
  • 42
  • 2
    FYI: `onkeyup` will not register multiple presses if the user holds a key down –  Jun 20 '18 at 07:54
4

Javascript:

function h(x) 
{
   alert(x); 
}

HTML Code:

<input onkeyup=h(this.value) type=text>
Nuri Ensing
  • 1,899
  • 1
  • 19
  • 42
-2
var unicode=e.keyCode? e.keyCode : e.charCode;
typing = document.getElementById('textbox').value + String.fromCharCode(unicode);
Wasim A.
  • 9,660
  • 22
  • 90
  • 120