Uffo
Uffo

Reputation: 10046

jQuery keydown/keypress not working right

So I haven an input:

<input type="text" name="in" />

And I need to get the current value of the input as I type, the problem that I face is, if I type pass and I do a console.log what I will get will be pas missing the last character; but I need to whole string pass

You can see a live demo here: http://jsfiddle.net/HjVHV/1/ What's the problem?

Upvotes: 1

Views: 218

Answers (5)

user1717828
user1717828

Reputation: 7225

Is this what you are looking for?

http://jsfiddle.net/qr59c/1/

I copied and modified the following block of code from http://forum.jquery.com/topic/can-change-handle-immediate-text-changes#14737000000967875

$('#input').each(function() {
 // Save current value of element
 $(this).data('oldVal', $(this));

 // Look for changes in the value
 $(this).bind("propertychange keyup input paste", function(event){
    // If value has changed...
    if ($(this).data('oldVal') != $(this).val()) {
     // Updated stored value
     $(this).data('oldVal', $(this).val());

     // Do action
     $('.output').html($('#input').val());
    }
 });
});

Upvotes: 0

Samyak
Samyak

Reputation: 137

You should use the key up event.

Here is the sample code based on your js fiddle

$('input').keyup(function(){
    $('.output').html($('input').val());
});​

Upvotes: 1

You could keep up using .keydown() if you want, just append the character pressed using .fromCharCode() , like this:

$('input').keydown(function(e){
    $('.output').html($('input').val() + String.fromCharCode(e.which).toLowerCase());
});

See working demo

Upvotes: 1

mgraph
mgraph

Reputation: 15338

you should use keyup :

$('input').keyup(function(){...

Upvotes: 4

user1796666
user1796666

Reputation:

You should use the keyup event:

$('input[name=in]').keyup(function()
{
  // $(this).val()
});

Inside you get the value you've just entered

Upvotes: 4

Related Questions