Countdown remaining text characters in an HTML text input with jQuery

Using this simple Javascript with jQuery code snippet, we can count down the number of Text characters remaining based on a limit we set. This is very similar to how Twitter’s status input shows how many text characters remain as you type in text.

For example, if we type in 20 text characters (including spaces) of 140 allowed, this will show 120 remaining. If we go over the 140 characters, then the counter div will be updates with a negative number and add the CSS class .overlimit which will change the counter text color to RED in my example below to show that it is in the negative range.

jQuery Code


$(document).ready(function(){
    var left = 140
    $('#text_counter').text('Characters left: ' + left);

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

        left = 140 - $(this).val().length;

        if(left < 0){
            $('#text_counter').addClass("overlimit");
        }
        if(left >= 0){
            $('#text_counter').removeClass("overlimit");
        }

        $('#text_counter').text('Characters left: ' + left);
    });
});

The HTML Text Input/Textarea and CSS


<style>
.overlimit{
   color: red;         
}​
</style>

<textarea id="status"></textarea>
<span id="text_counter"></span>

Example on JSFiddle

https://jsfiddle.net/jasondavis/BKEY3/

June 30 2012

Written by

Web-Developer from Central Florida. This blog is my outlet to what I am into at the time. PHP, Javascript, MySQL, OO Practices, Performance, Cool Software and Services, etc... Please subscribe to the RSS feed

  • tosbourn

    Nice idea – you could tidy up the code a little bit by doing something like;

            if( left < 0){
                $('#text_counter').addClass("overlimit");
            } else {
                $('#text_counter').removeClass("overlimit");
            }
    Then you don't need to do two if statements, which will make it slightly quicker.

  • http://zachs.co/ Zach

    do you know a way to make the textbox not editable at 0 characters left? Not the readonly attribute, just make it so nothing can be added.

  • mrgrizzle

    I added the extra line in the “if” in the hope it would disable the submit button on my form, but it didn’t… can anyone advise?

    if(left < 0){   $('input[type=submit]', this).attr('disabled', 'disabled');   $('#text_counter').addClass("overlimit");}