Q:

jQuery character counter issue

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');
              }
            }
        });
    });
});

http://jsfiddle.net/Mrbaseball34/RymcJ/16/

A:

There are a lot of things that could be improved about that script. The source of your problem is described by the comment:
// eat backspaces, tabs, and CRs

Next, it uses the keydown event, so it might have certain other problems. It also takes the count from the size attribute rather than the more correct maxlength attribute. Here's how I would rewrite it:
$(document).ready(function() {
    $('.word_count').each(function() {
        var $this = $(this);
        var counter = $this.parent().find('.counter');
        var maxlength = $this.attr('maxlength');

        counter.text('Only ' + maxlength + ' characters allowed');

        $this.bind('input keyup keydown', function() {
            var value = $this.val();

            if(value.length > 0) {
                counter.text((maxlength - $this.val().length) + ' characters left');
            } else {
                counter.text('Only ' + maxlength + ' characters allowed');
            }
        });
    });
});

Here's a demo.

