Reputation: 2297
I've looked at various posts on SO about this topic. I am making a character down-counter (ex. '98 Characters Left') for a textbox, the only event I can get it to fire for is keydown()
, but it doesn't handle it when text is pastes into the textbox. I have tried making an updateCharCount()
function and setting it to every event (all at one time, and each individually: keyup, keydown, keypress, change.
I have also tried setting the handler with bind()
and live()
. If I try to set the handler for keydown & keyup at the same time, neither of the fire, change just plain doesn't fire at all no matter what although everywhere I read that is the solution. How could this be?
Also, I am getting some strange behavior when I only handle the keydown()
event. (BTW I have the maxLength attribute on my textbox set to 100) If I type to the max character count, backspace once or twice, then type to the max count again, it will read '1 Character(s) Left' even though it is maxed out, and if I backspace once from there it reads '0 Characters(s) Left'. Here's my code:
function updateCharCount(){
var clientmsg = $("#usermsg").val();
var count = $("#usermsg").attr("maxLength") - clientmsg.length;
$("#charsleft").html(count);
}
$("#usermsg").keydown(updateCharCount());
If anyone could explain the strange behavior that would be nice, but what I REALLY want to know is why if .change() is so widely used, it doesn't work for me, nor .bind('change', ...) or .live('change', ...)
Upvotes: 2
Views: 3418
Reputation: 207900
You can bind multiple events using .on() (bind and live have been deprecated) like this:
$("#usermsg").on({
change: updateCharCount,
keyup: updateCharCount,
keydown: updateCharCount
})
Upvotes: 4
Reputation: 12815
Use keyup
instead of keydown
as keydown happens BEFORE symbol is inserted.
Change with text field will happen only when focus leave that field. If something changed, but not any time you add a symbol
Keyup will also handle paste event.
Upvotes: 1