Ateev Chopra
Ateev Chopra

Reputation: 1026

Getting characters in textarea on keyup

I want to get the number of characters in a textarea. This needs to update at every keystroke. So i used this simple function:

$(document).on('keyup', 'textarea', function () {
    var count = $(this).val().length;
    console.log(count); 
});

Now the problem is, If i try to type very fast, the count repeats. We can see the repetition in console. What is the reason behind this repetition ? Also how can i avoid it ? Here's a fiddle: https://jsfiddle.net/w6mzzfd8/

Thanks !

Upvotes: 1

Views: 335

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82241

As per Docs:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.

Solution:

Use keydown instead of keyup

Code:

$(document).on('keydown', 'textarea', function () {
 var count = $(this).val().length;
 console.log(count); 
});

Working Demo

Upvotes: 3

Related Questions