Alexander Seredenko
Alexander Seredenko

Reputation: 819

Wrong getting value when key is pressed

I try to get value from text input when key is down.

My code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="text" onkeydown="console.log(this.value)">
</body>
</html>

Code demo: http://jsbin.com/funexipure/1/edit?html,console,output

Trouble description:
When I write 1 I have "" as value in console.
When I write 2 after this I have "1" as value in console, and so on

So, How I can get actual current value when key is down? Thank you very much.

Upvotes: 2

Views: 56

Answers (2)

Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10177

Keyup function is quite good but it doesn't work if you paste the value with mouse click.

Try this

$('input').on('input propertychange', function(){
   console.log($(this).val());
})

This will work in keyboard typing also when you paste with mouse click.

Reason

keyup check when you press the key from keyboard but propertychange work when you change any property anyway.

Upvotes: 0

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

You can use onkeyupto get what desire output is

  <input type="text" onkeyup="console.log(this.value)">

Upvotes: 3

Related Questions