yellowbyte
yellowbyte

Reputation: 199

Get the current user input from the onkeydown event (Javascript)

I am able to print whatever user types into the textarea onto the console, but the output on the console doesn't print the most current character typed by the user. There is a picture of the result:

http://postimg.org/image/k44nyls9d/

Here is my code:

http://postimg.org/image/ynpl53cmv/

Thanks

(Sorry I can't directly upload the pictures. I don't have the 10 reputation that's required to post images since I just made the account)

Upvotes: 0

Views: 244

Answers (4)

Stanley Amos
Stanley Amos

Reputation: 232

since you're using jquery for it, try:

$('#myTextarea').keyup(function (){ console.log($(this).val());});

this will give you the current typed in the textarea

Upvotes: 0

Kristof Feys
Kristof Feys

Reputation: 1842

First of all, you can define the events in your jquery, no need to put this in your HTML. When you use keydown, the key isn't registered yet, this happens after this event is fired. You can simply bind change, keydown & keyup to cover all events and get the correct value.

$('#myTextarea').bind('change keydown keyup',function (){
   console.log($(this).val());
});

http://jsfiddle.net/KYhzK/

Upvotes: 1

Frederik.L
Frederik.L

Reputation: 5620

Try changing onkeydown to onkeyup. The keydown event more likely happens before the textbox has updated, so it will log the previous value instead of the new one.

Upvotes: 0

Mordalthunder
Mordalthunder

Reputation: 256

Your answer lays in the Events, you can use onkeyup event instead of onkeydown

onkeydown triggers when you press the keyboard key

onkeyup triggers when you release the keyboard key

Edit:

Since you are using Jquery:

$(document).ready(function(function(){
    $("#myTextarea").keyup(function(){
        console.log($(this).val());
    });
});

Upvotes: 0

Related Questions