Found this very simple code to show character counts for my text inputs:
http://www.jamesfairhurst.co.uk/posts/view/jquery_word_character_counter
I modified it like below. However it isn’t working correctly when backspacing. it doesn’t display the char count correctly. Can somebody help fix this?
$(document).ready(function() {
$('.word_count').each(function() {
$(this).parent().find('.counter').html('Only ' + $(this).attr("size") + ' characters allowed');
// bind on key up event
$(this).keydown(function(event) {
k = event.keyCode;
// eat backspaces, tabs, and CRs
if(($(this).attr("size") - $(this).val().length) == 0&&(k!=8&&k!=9&&k!=13)) {
event.preventDefault();
} else {
if($(this).val().length==0) {
$(this).parent().find('.counter').html('Only ' + $(this).attr("size") + ' characters allowed');
} else {
$(this).parent().find('.counter').html(($(this).attr("size") - $(this).val().length-1) + ' characters left');
}
}
});
});
});
There are a lot of things that could be improved about that script. The source of your problem is described by the comment:
Next, it uses the
keydownevent, so it might have certain other problems. It also takes the count from thesizeattribute rather than the more correctmaxlengthattribute. Here’s how I would rewrite it:Here’s a demo.