Reputation: 13937
So I'm doing character counting on a text field. I need to update the character count on keypress (not keyup). The issue is that with jquery's .keydown()
method, it refreshes the counter before the character is entered, so the counter is always 1 keypress behind the actual count. How can I get the count to change on keypress, but wait for the character to be entered?
Thanks!
Upvotes: 1
Views: 7056
Reputation: 97661
setTimeout
seems to work here:
$('input').keydown(function(e) {
var $this = $(this);
setTimeout(function() {
var text = $this.val();
console.log(text.length);
}, 0);
});
Upvotes: 9
Reputation: 26320
A simple example:
var MAX_CHARACTERS = 60;
$('textarea').bind('keyup keydown', function() {
var $element = $(this);
if($element.val().length > MAX_CHARACTERS) {
$element.val($element.val().substring(0, MAX_CHARACTERS));
}
$('.counter').val(MAX_CHARACTERS - $element.val().length);
});
Upvotes: 2
Reputation: 101533
Use .keyup()
instead. It's triggered when the key is released, so the counter will increment then.
From the documentation:
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.
You use it in the same way you would any other event:
$('input').keyup(function(e) {
var text = $(this).val();
console.log(text.length);
});
Make sure to count the number of characters in the text box (as in the example above), not the number of keys pressed. For example, pressing Ctrl + C would result in two extra characters counted, but none actually entered into the input.
If you're using jQuery 1.7+, use .on()
:
$('input').on('keyup', function(e) {
// Do your magic
});
Upvotes: 9