chovy
chovy

Reputation: 75804

Why does jQuery.keydown not fire the first letter I type?

Why does jQuery.keydown not fire the first letter I type?

http://jsfiddle.net/AstRc/

<input id="foo" type="text">
<div></div>

$("#foo").on('keydown', function(e){
    $("div").text(this.value);
});

I only see it fire on the 2nd keydown press, not the first.

Upvotes: 1

Views: 1108

Answers (3)

Fabien TheSolution
Fabien TheSolution

Reputation: 5050

If you really need to do the update in the keydown event, you can start with something that look like this but there will be many situations where this will not work as expected. You will have to manage many exceptions using the e.keyCode value

$("#foo").on('keydown', function(e){
    var content = $("div").text();
    $("div").text(content+String.fromCharCode(e.keyCode));
    if (e.keyCode==8) { $("div").text(content.slice(0,-1)); }
});

See JSFIDDLE

Upvotes: 0

JustWork
JustWork

Reputation: 1964

I am not sure if you are looking for solution but you can use instead:

$("#foo").on('keyup', function(e){
    $("div").text(this.value);
});

Upvotes: 1

Ry-
Ry-

Reputation: 225125

When the keydown event is being fired, the value in the textbox hasn’t changed yet. It seems like you’re looking for the input event anyways (use 'input keyup' for backwards compatibility). Updated fiddle

Upvotes: 3

Related Questions