I have this simple javascript function which counts the number of characters the user is able to enter in a text box/ text area:


how can I cater for any backspaces? (I a user deletes a character the number of characters left increases by 1)?


I've used this one before and it was dead easy to use. It was quite a clean and tidy addition to one of my major forms.

use keyup instead of keypress. just tried it and it worked better.

$('#txtbox').keyup(function() {

var textLen = $(this).val().length;
var textLeft = parseInt($(this).attr("maxlength")) - textLen;
    textLeft + ' character' + (textLeft == 1 ? '' : 's') + ' left'

I added the maxlength attibute to your textbox and just grapped that in the javascript just to make the acript a bit more re-usable.

I dont think that line 9 in your sample is needed.. or line 14 from the last jsfiddle example..yes/no?

line 9 - $('#txtbox').keyup();
jsfiddle, line 14 $('#txtbox').keypress();

that line is just starting the string when the page loads.

very helpful all, all I had to do was keyup instead of keypress and worked like a charm. THanks

keydown would be more accurate as it will fire when someone keeps the button pressed in as well.