jQuery tips & tricks: how to limit characters inside a textarea

You might have come across a problem trying to limit the maximum number of characters in a text area, since a maxlength attribute doesn’t exist for this tag. In this article we will provide you with a jQuery-based solution, one that is fully functional and usable.

The concept is based on counting all the characters in a text area every time you release a keystroke without allowing any more characters to be added. At the same time, we will calculate the difference between the maximum number of characters allowed and their actual number, thereby showing us in realtime the number of characters remaining. You can see the final result in this example page.

The importance of doing client checks on a form

When we carry out client checks(as in this example) on a form, we must be aware that we are doing it solely to help the user, to make the site more usable. It is very important to note that client checks are easily bypassed, so the real check-up (length, format, etc.) must be done on a server. Having said this, we can move on to the main subject.

Setting up the page

Let’s begin by setting up a text area form inside a new html page.  Next we will add a blank div (#counter), containing a phrase on the number of characters remaining.

<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script  type="text/javascript" src="jquery-1.4.1.js"></script>
    <script  type="text/javascript">
        $(document).ready(function() {
        // here we will write-up the function
        });
    </script>
</head>
<body>
    <form  id="input_form"  method="POST" action="?">
    <textarea  id="text"></textarea>
    <input type="submit"  value="submit">
</form>
<div  id="counter"></div>
</body>
</html>

Now we are ready to write up the function. Let’s start by defining the character variable which stands for the maximum number of characters that a text area can contain. Next let’s write up the phrase in the counter element.

var characters= 100;
$("#counter").append("You have  <strong>"+ characters+"</strong> characters remaining");

Now every time that the keyup event takes place (everytime you release a keystroke) we will proceed with the check-up:

$("#text").keyup(function(){
    if($(this).val().length > characters){
        $(this).val($(this).val().substr(0, characters));
}

This check-up can look quite complex, but we will see in a moment what it’s all about.

With $(this).val() we extract the actual content of the textarea (at the time of keyup) and length gives us the number of characters. If this number is greater than what we’ve set in the character variable (100 in this case), the textarea content will have to be the same as the textarea content which passed through the substr function with parameters 0, and characters.

The substr function cuts off a piece of the string; parameters indicated where the characters begin and end by being cut off. Thus in our case it begins at 0 (the beginning of the string) and ends at characters (character 100).

Summing up: if the length of the string contained in the textarea is greater than the maximum number we’ve set, you should cut the string at a length equal to the maximum number of set characters.

Now let’s change the phrase with the remaining number of characters:

var  remaining = characters - $(this).val().length;
$("#counter").html("You have <strong>"+ remaining+"</strong> characters remaining");

Here we will simply subtract the number of characters written in the textarea from characters and we will insert the resulting phrase in the counter element.

Let’s add a little tweak. If the number of remaining characters is less than ten, the phrase will be written in red, in the following way:

if(remaining <= 10)
{
    $("#counter").css("color","red");
}
else
{
    $("#counter").css("color","black");
}

The final script should look like this:

$(document).ready(function()  {
    var characters = 220;
    $("#counter").append("You have <strong>"+  characters+"</strong> characters remaining");
    $("#text").keyup(function(){
        if($(this).val().length > characters){
        $(this).val($(this).val().substr(0, characters));
        }
    var remaining = characters -  $(this).val().length;
    $("#counter").html("You have <strong>"+  remaining+"</strong> characters remaining");
    if(remaining <= 10)
    {
        $("#counter").css("color","red");
    }
    else
    {
        $("#counter").css("color","black");
    }
    });
});

jQuery: the logic behind extensions

Now that we have a script which we can use more than once, it’s only right to follow the logic behind jQuery and turn it into a plugin.

Let’s begin by setting up the structure of the plugin:

(function($){
    $.fn.limit = function(options) {

Our method is called limit and it can run various parameters. Let’s start by setting up the default ones

var  defaults = {
    limit: 200,
    id_result: false,
    alertClass: false
}

As you can see, parameters will be the maximum number of characters, the element id containing the phrase which indicates the remaining number of characters (by default this does not exist) and the css class which determines the color (and/or other attributes) which will affect the text if there are less than 10 characters.

This method is correct, more so than the one we saw earlier. In fact who said that the text should become red? Furthermore who said that text should be in black from the very beginning? In this way, we will not use css methods but addClass and removeClass so that the style can be configured directly from css.

Now let’s enhance the options available:

var options =  $.extend(defaults, options);

Now let’s write up the function being careful in printing out the phrase only if the id_result parameter has been enhanced:

return this.each(function() {
    var characters = options.limit;
    if(options.id_result != false)
    {
        $("#"+options.id_result).append("You have <strong>"+  characters+"</strong> characters remaining");
    }
    $(this).keyup(function(){
        if($(this).val().length > characters){
        $(this).val($(this).val().substr(0, characters));
        }
        if(options.id_result != false)
        {
            var remaining =  characters - $(this).val().length;
            $("#"+options.id_result).html("You have <strong>"+  remaining+"</strong> characters remaining");
            if(restanti <= 10)
            {
                $("#"+options.id_result).addClass(options.alertClass);
            }
            else
            {
                $("#"+options.id_result).removeClass(options.alertClass);
            }
        }
    });
});

Here is the plugin in complete form:

(function($){
    $.fn.limit  = function(options) {
        var defaults = {
        limit: 200,
        id_result: false,
        alertClass: false
        }
        var options = $.extend(defaults,  options);
        return this.each(function() {
            var characters = options.limit;
            if(options.id_result != false)
            {
                $("#"+options.id_result).append("You have <strong>"+  characters+"</strong> characters remaining");
            }
            $(this).keyup(function(){
                if($(this).val().length > characters){
                    $(this).val($(this).val().substr(0, characters));
                }
                if(options.id_result != false)
                {
                    var remaining =  characters - $(this).val().length;
                    $("#"+options.id_result).html("You have <strong>"+  remaining+"</strong> characters remaining");
                    if(remaining <= 10)
                    {
                        $("#"+options.id_result).addClass(options.alertClass);
                    }
                    else
                    {
                        $("#"+options.id_result).removeClass(options.alertClass);
                    }
                }
            });
        });
    };
})(jQuery);

Now, if we wanted to obtain the same result we witnessed in the first part by using the plugin, we will have to include this plugin and modify the code in the following way (let’s remember to create a css class):

<script  type="text/javascript" src="jquery-1.4.1.js"></script>
<script  type="text/javascript" src="jquery.limit.js"></script>
<style>
.alert{
    color: red;
}
</style>
<script  type="text/javascript">
    $(document).ready(function() {
        $("#testo").limit({
            limit: 100,
            id_result: "counter",
            alertClass: "alert"
            });
         });
</script>
download
Versione: 1.0
Pubblicato: 16 May 2010
Dimensione: 912 bytes
Download: JQueyLimit

Conclusion

We’ve just looked at the beautiful modularity of jQuery. Any problem, recurring ones included, can be resolved with an extension. If we adopt this approach, we could end up creating a huge collection of plugins. Their use in the code provides for easy reading and aesthetically pleasing as well.
In this article we’ve described a possible procedure to use to limit the length of a text inside a text area.
Did you ever come across a similar procedure? How did you manage to solve the embedded problem?

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: ,

The Author

Maurizio is married to the triad PHP - MySql - Apache and, not enough, he has a lover called jQuery. He has a blog where he tries to describe in detail all of "his lovers". His real specialty is the realization of large business application, altough he never refuses the commitment of a website.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

35 comments

  1. Maya
  2. A. León
  3. Laurent
  4. Devinity Now
  5. Nathan
  6. Sachin
  7. Jana
  8. Dom
  9. Frank
  10. 10zil
  11. Ashish

Trackback e pingback

  1. Tweets that mention jQuery tips & tricks: how to limit characters inside a textarea | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by Paul, nando pappalardo, Your Inspiration Web, Tom Bangham, V. Tavares (E-Goi) and …
  2. Element with jquery |Avnish Namdev
    [...] [ 11 Comments ] [...]
  3. [RESOLVED]How to restrict the character display while typing in javascript | ASP Questions & Answers
    […] http://www.yourinspirationweb.com/en/jquery-tips-tricks-how-to-limit-characters-inside-a-textarea/ […]
  4. [RESOLVED]How to restrict the character display while typing in javascript | ASP Web Form Data Control
    […] http://www.yourinspirationweb.com/en/jquery-tips-tricks-how-to-limit-characters-inside-a-textarea/ […]
  5. Mudahnya Membatasi Jumlah Karakter di TextArea Aplikasi Web dari PHPMaker – Masino Sinaga
    […] ini saya peroleh dari website: http://www.yourinspirationweb.com/en/jquery-tips-tricks-how-to-limit-characters-inside-a-textarea/, kredit buat om Maurizio […]
  6. Beauty Tips Jquery Download | Beauty Eats
    […] jQuery tips & tricks: how to limit characters inside a … – You might have come across a problem …
  7. Beauty Tip Jquery Plugin | dibeauty.com
    […] jQuery tips & tricks: how to limit characters inside a … – You might have come across a problem …
  8. Beauty Tips Jquery Download | Toe Beauty
    […] jQuery tips & tricks: how to limit characters inside a … – You might have come across a problem …

Leave a Reply

Current day month ye@r *