Reputation: 2365
I completely understand the method of using .bind('keyup', function() { });
to count characters in a textarea
or input
, but I've attempted to do a keydown
function so you can see the results AS you're typing, versuses, holding down a letter on your keyboard and the count not updating until AFTER you've released the key.
var input = $('textarea#input');
$('span#character-count').text(input.val().length);
input.bind('keydown', function() {
$('span#character-count').text(input.val().length + 1);
});
My current method is flawed:
jsFiddle: http://jsfiddle.net/rdvR7/
Upvotes: 1
Views: 6392
Reputation: 13164
Bind "keyup" event when user select text in textarea:
var input = $('textarea#input');
$('span#character-count').text(input.val().length);
input.bind('keydown', function(e) {
$('span#character-count').text(0);
input.select( function () {
input.bind('keyup', function(e) {
$('span#character-count').text(input.val().length);
})
});
$('span#character-count').text(input.val().length);
});
Jsfiddle: http://jsfiddle.net/glenswift/SEBLD/1/
You can also combine bindidng "keydown" and "keyup":
var input = $('textarea#input'),
firstInput = true;
$('span#character-count').text(input.val().length);
input.bind('keydown, keyup', function(e) {
$('span#character-count').text(0);
$('span#character-count').text(input.val().length);
});
Jsfiddle: http://jsfiddle.net/glenswift/L6DR8/1/
Upvotes: 0
Reputation: 150020
I'd suggest that an accurate count on keyup is better even if it is momentarily wrong while a key is held down, because in practice I think users don't often need the same character repeated so they don't tend to hold a single key down, and it keeps the code simple. But if you want keydown...
"it requires +1 to show a live view"
I assume you realise that that is because the current value of the field during processing of the keydown event doesn't include the change associated with the keystroke - if it did you couldn't cancel the keydown event without having to undo the change.
A simple way to work around that is to delay updating the count until after the keydown event has finished, perhaps like this:
var input = $('textarea#input'),
count = $('span#character-count').text(input.val().length);
input.bind('keydown', function() {
setTimeout(function() {
count.text(input.val().length);
},4);
});
Updated demo: http://jsfiddle.net/nnnnnn/rdvR7/2/
Note that the user can add or remove text without triggering a keyboard event at all (through drag'n'drop or cut/paste).
Upvotes: 5