nav-left cat-right
cat-right

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. 

Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Wists
  • Furl
  • Ma.gnolia
  • NewsVine
  • Reddit
  • Simpy
  • StumbleUpon
  • Technorati


50 Responses to “Interactive character limit for textarea using Jquery”

  1. Jahed BANGLADESH says:

    Nice Job done. But why prototype is not given?

  2. admin BANGLADESH says:

    If you are using prototype for your site, you can use the second function. It doesn’t depends on jQuery.

  3. 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.

  4. Paulo BRAZIL says:

    Hi man,

    Can you send the source of this template to my email address ? I like it too much.

    Thx.

  5. admin BANGLADESH says:

    @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.

  6. admin BANGLADESH says:

    @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.

  7. Sam SWITZERLAND says:

    Sweet…….exactly what i needed!!!!!!!! thx!

  8. 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

  9. admin BANGLADESH says:

    Thanx Emran vai,
    It’s simply Excelent!
    I cannot understand how did I miss this logic.
    Thanx a lot again.

  10. Dario ITALY says:

    Sweeeeeeet and elegant! Thank you so much! ;)

  11. Idetrorce ROMANIA says:

    very interesting, but I don’t agree with you
    Idetrorce

  12. Darkimmortal UNITED STATES says:

    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.

  13. satts INDIA says:

    interesting code..exactly what i was looking for

  14. Eireannwu CHINA says:

    thats it, guy

  15. Frank GERMANY says:

    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.

  16. henning GERMANY says:

    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?

  17. Pwhndvve says:

    Thousands and look closer buy cytotec then announced estivities.

  18. JutyCols AUSTRALIA says:

    @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.

  19. Axthos Bryce MEXICO says:

    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.

  20. Wesley says:

    Thanks, nice code – will be saving it in my library :)

  21. [...] character limiter for jhoroTEK SMS server reporting panel. Then i found this one in ajaxray’s blog.  Though i liked the code much but writting some extra targeted code seems too much for me. So, i [...]

  22. Gerrit UNITED STATES says:

    Great script, works perfectly! Thanks!

  23. John UNITED KINGDOM says:

    Hi. Lovely little solution, thanks for posting it up.

  24. tlad INDIA says:

    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 .

  25. tlad INDIA says:

    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 .

  26. Anis Ahmad HONG KONG says:

    Hi Friend,
    I’ve tested it in FF and IE7 and everything works fine.
    http://www.ajaxray.com/Examples/charLimit.html

    Can you please tell me about your OS and Browser?

    Thanks

  27. tlad INDIA says:

    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

  28. [...] Text Limiter Search this site [...]

  29. Angela UNITED STATES says:

    Is there a way to include the javascript without putting it all into the view/html.erb?

  30. Angela UNITED STATES says:

    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?

  31. Ben Palmer UNITED KINGDOM says:

    Thanks very much for this, really helpful in making a little Twitter box in a CMS i am currently building

  32. Thanks Anis vai, just used this in a joomla form builder component’s mambot.

  33. Farooq UNITED ARAB EMIRATES says:

    Thanks for very useful script, small and useful script

  34. Juan says:

    Very useful! Thanks dude

  35. Achutha Krishnan INDIA says:

    That was a good demo http://www.ajaxray.com/Examples/charLimit2.html.

    But what if the User Drags selected text and drop the text in the TextBox? It fills with more than the limit.

  36. jrock UNITED STATES says:

    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!

  37. webCV AUSTRALIA says:

    Thanks for a hot script, very useful!

  38. Arun Kumar GJ INDIA says:

    Thanks a lot Mr.Anis Ahmad, its very useful to me.

  39. Sotiria FRANCE says:

    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?

  40. tchalvak says:

    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.

  41. tchalvak says:

    Err, javascript-less accessible, that should have said. *winks*

  42. Federico URUGUAY says:

    Hello,

    If I include this function into my project, I must include a link to your web page?

    Regards.

  43. 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 :)

  44. Thanks, this tutorial really helped me. Great job!

  45. [...] Interactive character limit for textarea using Jquery [...]

  46. Dumka ESTONIA says:

    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:

    $(document).ready(function() {
    // Define handler function
    function CountCommentLength(){
    limitChars('comment', 20, 'charlimitinfo');
    }
    // Assign handler to following events:
    $('#comment').keyup(CountCommentLength);
    $('#comment').mousedown(CountCommentLength);
    
  47. a1945 AUSTRALIA says:

    nice artikel but why you don’t show demo

  48. Cabanossi FINLAND says:

    I get the following error on every keypress:

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

  49. Anis Ahmad HONG KONG says:

    @a1945
    Here is the demo:
    http://www.ajaxray.com/Examples/charLimit.html

    @Cabanossi
    Can you please mention your browser and OS?

    @Jameshd
    Thanks for sharing here.

    Thanks a lot to all of you for you.

Leave a Reply