Interactive character limit for textarea using Jquery

For a textbox, character of a field can easily be limited with maxlength attribute. But maxlength doesn’t work for  a textarea. So, It needs an alternate way. For one of my project, I wrote a function for this purpose where I used jQuery. Here I am explaining how I did it.

Let’s look an example of this interactive solution here

OK. Now we will make this in 2 easy steps.

1. Import your jQuery file and write the function "limitChars(textid, limit, infodiv)" in the head section of your page.

This function takes 3 parameters. They are:

  • textid : (string) The ID of your textarea.
  • limit : (num) The number of character you allow to write.
  • infodiv : (string) The ID of a div, in which limit information will be shown .

  Here is the function:

 1: <script language="javascript" src="Jquery.js"></script>
 2: <script language="javascript">
 3: function limitChars(textid, limit, infodiv)
 4: {
 5: var text = $('#'+textid).val(); 
 6: var textlength = text.length;
 7: if(textlength > limit)
 8: {
 9: $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
 10: $('#'+textid).val(text.substr(0,limit));
 11: return false;
 12: }
 13: else
 14: {
 15: $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
 16: return true;
 17: }
 18: }
 19: </script>

Remember, the script is using jQuery. So be careful about the path of jquery at first line of this script.
 
2. Bind the function to the keyup event of your textarea. Do this in jQuery’s ready event of document. Just like this:
 1: $(function(){
 2: $('#comment').keyup(function(){
 3: limitChars('comment', 20, 'charlimitinfo');
 4: })
 5: });

Here my textarea’s id is ‘comment’ , limit of characters is 20 and limit information will shown in a div whose id is ‘charlimitinfo’. That’s all, we have made an "Interactive character limiter" for our textarea using Jquery.
 
If you are not using jQuery for your site, it will not be wise to include it only for this script. You can get the same functionality from javascript without jquery. Look at this example. It looks like and works 100% as the previous though not using jquery.
Here you need just 2 changes. First, change the function "limitChars" as follows :
 1: function limitChars(textarea, limit, infodiv)
 2: {
 3: var text = textarea.value; 
 4: var textlength = text.length;
 5: var info = document.getElementById(infodiv);
 6:  
 7: if(textlength > limit)
 8: {
 9: info.innerHTML = 'You cannot write more then '+limit+' characters!';
 10: textarea.value = text.substr(0,limit);
 11: return false;
 12: }
 13: else
 14: {
 15: info.innerHTML = 'You have '+ (limit - textlength) +' characters left.';
 16: return true;
 17: }
 18: }

 
And finally, call the function manually on keyup event of your textarea. Use "this" keyword for textarea instead of id when calling the function. example:
 1: <textarea name="comment" id="comment" onkeyup="limitChars(this, 20, 'charlimitinfo')">
 2: </textarea>

Finished. We made the solution again without dependency of any javascript framework.

Please let me know if you have an idea to make it better. 

82 Comments

  1. The only full proof way to do this is actually with a timer that checks the length of the input in intervals. If I type more than 20 characters in notepad, then copy it, and use Edit >> Paste in the browser window, it will allow more than 20 for this example.

  2. @Brian Reindel:
    Hi friend,
    I think, javascript cannot make anything “full proof” when a user wants to hack. Because, most of browsers allow a user to disable javascript. So, front end validations just alert a user about invalid inputs on a pre-submission stage. Sensitive issues must validate again from back end.
    Thanx a lot.

  3. @paulo :
    Hi,
    Thanks for your interest. There is no any server script uses in this demo. So, you can easily get the source from browsers “view source” option.

  4. Hey Anis!

    Thats a very nice piece of code you’ve crafted. I would like to suggest a small tweak, to make life easy for people who wants to implement this.

    So, instead of writing these code:

    $(function(){
    $(‘#comment’).keyup(function(){
    limitChars(‘comment’, 20, ‘charlimitinfo’);
    })
    });

    …how about making it more simple like this:

    $(function(){
    limitChars(‘comment’, 20, ‘charlimitinfo’);
    });

    …and you hook the things up for the keyup event in your function itself ? In this way, i won’t need to bother whether its keyup or keypress, as you’ll choose whats best.

    Thanks

    Emran

  5. Very nice code – I will definitely be using this.

    And also, that Paulo guy that was asking for the template as far as I can tell he means the template of this actual site (which is indeed very nice), not the javascript.

  6. I don’t want newline/linebreaks to be counted as character. So i’ve changed this:

    var text = $(‘#’+textid).val();

    to this;
    var text = $(‘#’+textid).val().replace(new RegExp( “\n”, “g” ),””);

    Maybe it’s helpfull for someone else.

  7. hello,

    i’ve searched in the web for counting characters with jquery and i found your page with Characters Remaining Countdown.

    now i have question:
    how i can manage that the count relate to both textfields.
    so for example:

    textfield 1: 5 char
    textfield 2: 6 char
    totalcount: 11 char

    i’ve tried to copy the textfield and name it the same, but did not work.

    how can i get this?

  8. @admin:

    Hi,

    im having this error “too many characters in character literal”

    hers’s my code:

    Mailing Address
    (if different from address of Organisation, max 200 characters.)

    :

    Write your comment within 200 characters.

  9. Hello, great code, but i was still able to write more than the allowed characters by typing and clicking elsewhere in the website without releasing the key…

    I switched the event from keyup to keydown….

    Looking like this:

    $(‘#title’).keydown(function(){
    limitChars(‘title’, 100, ‘info_title’);
    });

    And so far it has worked just fine.

  10. sorry some typo…
    Hi,
    nice code but can any one face issue like ctrl+a ctrl+x not working in it.

    I select all with key board short cut but while try to cut with shortcut the selected text disselect.
    I m not using jQuery.

    Thanks,
    tlaad .

  11. sorry some typo…and some case missing pls ignore previous

    Hi,
    nice code but can any one face issue like ctrl+a ctrl+x not working in it when text arear is enterd with its all limit characters.

    I select all with key board short cut but while try to cut with shortcut the selected text disselect.
    I m not using jQuery.

    Thanks,
    tlaad .

  12. Hi,
    Thank you,
    Previous problem is solve with some correction.
    but now some other proble as follows. Kindly help.

    following is my code:

    var count = 2000;
    function limiter() {
    var tex = document.charityDescriptionSave.charityDescription.value;
    var len = tex.length;
    var remaningcount = count-len;

    if (len > count) {
    tex = tex.substring(0, count);
    document.charityDescriptionSave.charityDescription.value = tex;
    document.getElementById(‘remainidCharacterCount’).innerHTML = “No”;
    return false;
    }
    else if (len < count) {
    document.getElementById(‘remainidCharacterCount’).innerHTML = remaningcount;
    return true;
    }
    markUpdated();
    }

    with the above code facing a issue like if user enter full data in text area till max limit. and then try to delete a single word or character by selecting it. it delete all the data from text box.

    Regards
    T

  13. nix the above, I put it into the application.js…HOWEVER, I am not seeing the added which shows the actual text. Do I need to do something to get that part to work?

  14. Neat function.

    However, hitting the ‘enter’ key only registers as one character. A user can hit enter multiple times then copy in their text and be well beyond the intended character count. Is there a workaround to handle copy and paste issues and/or the enter key only registering as one character?

    Thanks!

  15. Hello. Hello , i am totally new in Joomla. I need to add limited number of characters and propably the number of characters left in the textarea. I have a script that does the work but where should i put it? how the form is structured? I have found in the Community builder the Tab that contains the textareas and in the field Manager the text area. But there is no html editor or a way to see the html. How do i make changes?where are the html page?

  16. Here is was my reinterpretation, to be completely javascript-less in-accessible:

    Create a span with text saying: “500 character limit” under the text area. Give the span the appropriate id (in my case ‘characters-left’), then:
    //Call the function on keypress
    $(document).ready(function() {
    $(function(){
    $(‘#player-profile-area’).keyup(function(){
    textAreaCount(‘player-profile-area’, 500, ‘characters-left’);
    })
    });
    });

    // Change the text when the function is called.
    function textAreaCount(textareaid, limit, infoid){
    var textArea = $(‘#’+textareaid);
    var text = textArea.val();
    var textlength = text.length;
    var info = $(‘#’+infoid);
    var newText = limit+” character limit, “+textlength+” characters used.”;
    info.text(newText);
    }

    So if there’s no javascript, they at least know the limits intended, and with javascript they get a count as opposed to bothering with any hard limit.

  17. Thanks a lot for the gr8 script. I just added to my ‘teaser’ page and it worked gr8. Forgot to add onkeyup but still it worked gr8.

    Probably thats why your page appears at top on the search result 🙂

  18. Hi!

    Nice script but…

    If a user is pasting a text using his/her mouse (right button click -> paste), then characters won’t be counted!

    Solution – add same event handler for onMouseDown event. jQuery sample:
    [code]
    $(document).ready(function() {
    // Define handler function
    function CountCommentLength(){
    limitChars(‘comment’, 20, ‘charlimitinfo’);
    }
    // Assign handler to following events:
    $(‘#comment’).keyup(CountCommentLength);
    $(‘#comment’).mousedown(CountCommentLength);
    [/code]

  19. I get the following error on every keypress:

    Warning: The ‘charCode’ property of a keyup event should not be used. The value is meaningless.

  20. Anis, how does your script compare to the one at http://www.mediacollege.com/internet/javascript/form/limit-characters.html ?

    To be honest, I know very little about JavaScript and it’s hard to decide which one is better.

    At any rate, I’m already using PHP to prevent users from entering more than the allotted number of characters into my form’s textarea. I have also included a “title” attribute for the textarea’s parent div with the value of “250 characters max”. (Of course, users will not see that tooltip if they use the keyboard to tab through the form’s fields instead of navigating with the mouse.) But the main reason for using a JavaScript function like yours and the other one I referred to would be to give users feedback on when they are approaching the character limit.

  21. This was an awesome solution! I added a couple of small additions and made some small tweaks- maybe you’ll find them interesting. Thank you!

    // Note: Apply with the following:
    //
    //
    function imposeMaxTextLength(textarea, limit, infodiv) {
    var text = textarea.value.replace(/n/g, “rn”);
    var textlength = text.length;
    var info = document.getElementById(infodiv);

    if (textlength > limit) {
    if (info != null)
    info.innerHTML = ‘Limited to ‘ + limit + ‘ characters!’;
    textarea.value = text.substr(0, limit);
    return false;

    } else {
    if (info != null)
    if (textlength >= limit – 25)
    info.innerHTML = ‘Limited to ‘ + limit + ‘ characters (‘ + (limit – textlength) + ‘ left).’;

    else
    info.innerHTML = ”;
    return true;
    }
    }

  22. That was meant to read:
    // Note: Apply with the following:
    // <textarea onkeyup=”imposeMaxTextLength(this, 250, ‘maxtextlengthlimitinfodiv’)”></textarea>
    // <div id=”maxtextlengthlimitinfodiv”></div>

  23. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

  24. great script. well written, works like a charm.

    jquery is really begining to amaze me. I am using it with PHP, and together they can achieve almost anything.

  25. Hi,

    I’m a beginner in programming but i wondered something. How do you let html read the select items. I mean can you do something with the different variables?

    Byeee

  26. Nice work!!

    I changed this so you can use it on multiple textarea/text boxes using a class name that both identifies the element and info div to edit + the class name actually says how many chars to limit – thus each textarea/text box can have different char lengths on them via the class name – no more changing the JavaScript!!

    See explaination in main function

    // Main function
    function limitChars(className)
    {
    /* Expecting className format to be: limitchars_uniqueName_20 – the underscores ‘are key’ to this working, see split below
    * Where:-
    * limitchars: is mandatory to fire this event
    * uniquename: identifies your element and matches the related ‘info’ div
    * 20: character limit
    *
    * Matching info div format should be: uniqueName_info
    */
    var identifier = className.split(‘_’)[1];// get uniqueName part of class
    var limit = className.split(‘_’)[2];// get char limit
    var text = $(‘.’+className).val();
    var textlength = text.length;
    if(textlength > limit)
    {
    $(‘.’ + identifier + ‘_info’).html(‘You cannot write more then ‘+limit+’ characters!’);
    $(‘.’+className).val(text.substr(0,limit));
    return false;
    }
    else
    {
    $(‘.’ + identifier + ‘_info’).html(‘You have ‘+ (limit – textlength) +’ characters left.’);
    return true;
    }
    }

    //Event caller
    $(‘[class^=”limitchars”]’).keyup(function(){
    limitChars(this.className);
    });

    //Example html of two separate boxes

    Write your comment within 10 characters.

    Write your comment within 5 characters.

    Cheers
    eltreno

  27. Missing HTML from above example

    //Example html of two separate boxes
    <textarea rows=”3″ cols=”40″ name=”something1″ class=”limitchars_uniqueone_10″></textarea><br />
    <span class=”uniqueone_info”>Write your comment within 10 characters.</span>
    <br /><br />
    <textarea rows=”3″ cols=”40″ name=”something2″ class=”limitchars_uniquetwo_5″></textarea><br />
    <span class=”uniquetwo_info”>Write your comment within 5 characters.</span>

    Cheers
    eltreno

  28. did not work for me… I am accepting double byte chars(japanese) as an input…,But it fails..

    It starts inputting chars from begining of the text box….please help

  29. Hello,
    Is there any tutorial that can show me step by step how to implement it? I will really appreciate.

    For example, I would like to know where I should paste the code?

    Thanks!

  30. Great script, but l wish you had a better way to post code snippets on your blog. I grabbed the code from your demo page, but you should have one of those “plain text” popup buttons at least 😉

    Thanks again man!

Leave a Comment

Your email address will not be published. Required fields are marked *