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

http://jsfiddle.net/9XhDK/

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

Thanks

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;
$('#charCount').text(
    textLeft + ' character' + (textLeft == 1 ? '' : 's') + ' left'
);
});
$('#txtbox').keyup();

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

Member Avatar for stbuchok

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.