Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Last character missing on OnKeyPress event

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'

like image 877
Wasim A. Avatar asked Mar 17 '11 14:03

Wasim A.


People also ask

What is the difference between onKeyDown and Onkeypress?

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.

How do you get the value of a Keydown event?

The simple solution: just use the keyup event (and not the keydown event). This will give you the latest value after the user typed the latest character. That resolves the issue.

What happens when Onkeypress returns false?

If onkeyPress returns false, the key-down event is cancelled.

What is function of Onkeypress in keyboard event?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .


2 Answers

Javascript:

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

HTML Code:

<input onkeyup=h(this.value) type=text>
like image 45
nrii Avatar answered Oct 21 '22 13:10

nrii


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

like image 191
Lixas Avatar answered Oct 21 '22 13:10

Lixas