Start New Discussion within our Web Development Community

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)?


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();

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.

This article has been dead for over six months. Start a new discussion instead.