How to:Set Maxlength of Textarea using jQuery/JavaScript

Maxlength of Textarea

Update: The maxlength plugin is now managed at GitHub. Please contribute to make this plugin more awesome. GitHub: https://github.com/viralpatel/jquery.maxlength Setting up maxlength of input text are easy. Just an attribute maxlength="##" does the work. But maxlength attribute does not work with textarea. I tried writing <textarea rows=”5″ cols=”30″ maxlength=”120″></textarea> but this does not works. So what to do if we want to fix the maxlength of a textarea? Use following jQuery plugin for setting maxlength of any textarea on your page. First thing for doing is to add maxlength="XX" attribute in your <textarea> tag.
<textarea maxlength="15" rows="5" cols="30" name="address"></textarea>
Code language: HTML, XML (xml)
Include the jQuery plugin javascript file in your html page where the textarea is.
<script language="javascript" src="jquery.maxlength.js"></script>
Code language: HTML, XML (xml)
And, add following code snippet at the end of your html page.
<script type="text/javascript"> jQuery(document).ready(function($) { //Set maxlength of all the textarea (call plugin) $().maxlength(); }) </script>
Code language: JavaScript (javascript)
That’s it.. This jQuery plugin will search every textarea on your page and restrict the user to enter text till the maxlength. Following is the code of plugin
/* * jQuery Maxlength plugin 1.0.0 * * Copyright (c) 2013 Viral Patel * //www.viralpatel.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php */ ;(function ($) { $.fn.maxlength = function(){ $("textarea[maxlength], input[maxlength]").keypress(function(event){ var key = event.which; //all keys including return. if(key >= 33 || key == 13 || key == 32) { var maxLength = $(this).attr("maxlength"); var length = this.value.length; if(length >= maxLength) { event.preventDefault(); } } }); } })(jQuery);
Code language: JavaScript (javascript)

Demo

Download

GitHub: https://github.com/viralpatel/jquery.maxlength Download the Plugin file here. jQuery Plugin for setting maxlength of textarea. Feel free to extend the functionality of this plugin and also use it and let me know your comments.
Get our Articles via Email. Enter your email address.

You may also like...

36 Comments

  1. gaurav says:

    cool code.. Thanks viral .. .this code helps me a lot..

  2. webcook says:

    hi viral
    great job thanks :D

  3. Viral says:

    Thanks Webcook for the comment. :)

  4. Very good, but on paste large texts this script crashes….

  5. SS says:

    Good Code. But not handled the paste situation

  6. Suji says:

    ya its great code!!!
    If we want to Set Max Length TextArea OnPaste
    use the following code
    function maxLengthPaste(field,maxChars){
    event.returnValue=false;
    if((field.value.length + window.clipboardData.getData(\"Text\").length) > maxChars) {
    return false;
    }
    event.returnValue=true;
    }

    Use OnPaste Went To Call This Function
    onpaste=\"return maxLengthPaste(this,500)\"

  7. Juanpe says:

    And the space key?

  8. Breaking News says:

    You should not use a strict doctype, when you use this on your own pages, as there is no “maxlength” attribute defined in textarea. A “great” solution should include that information, at least, then show a way out of the dilemma.

    I do actually use a quite similar solution for my textareas, but neither am I happy about it, nor would I call my idea a great solution. It is the usual crap, which the W3C imposes on us.

  9. Anthony says:

    I have extended this in my own use to be able to take an extra setting to say what the attribute should be. I did this because when I am using asp.net, their standard textbox with multiline set removes the MaxLength property during rendering and never makes it to the screen.

    Thanks for this plugin.

  10. Victor says:

    SPACE character checks.

    Add the following before the current check for keystrokes. This keeps the user from entering spaces.

    // If current length is equal to the max and they enter
    // a space using the space bar then cancel
    if (key == 32) {
    var maxLength = $(this).attr(“maxlength”);
    var length = this.value.length;
    if (length == maxLength) {
    event.preventDefault();
    return;
    }
    }

  11. I would like to have certain specific elements have a greater z-index than inital set vale as lorenzo suggests, however am not sure what extra jQuery code i need to do this, have tried
    $(”.bridge”).css(”z-index”,”50000″); but dosent seem to have any effect, if anyone can point me in right direction be much appreciated

  12. Dave says:

    This is a simple plugin that worked for exactly what I needed.

    As of jQuery 1.3 though, the @attr syntax is no longer being used. Moving forward you should change \"textarea[@maxlength]\" to \"textarea[maxlength]\" in the plugin.

  13. Andrea says:

    Does not work with COPY/PASTE.

  14. Akash Bavlecha says:

    Make it work when copying and paste text into text area above!

  15. thomasp says:

    It’s works if you CHANGE $(“textarea[@maxlength]”) TO $(“textarea[maxlength]”) on line 16.
    I think that @ selector are depreciated.

  16. BenTheTipsyBear says:

    This would be much more useful revised to recalculate with spaces and backspaces.
    The cut and paste issue should be rolled in as well…
    Thanks!

  17. BenTheTipsyBear says:

    Okay – the spaces and backspaces are easy enough to add:
    Replace:
    if(key >= 33 || key == 13) {
    With:
    if(key >= 32 || key == 13 || key == 8) {

    Cheers!

  18. Gurinder says:

    Try pasting a long text , This plugin will fail.

    • @Gurinder: Ofcourse pasting something will not work as already mentioned above. I will soon modify the code and try to fix this. :)

  19. My version, compatible with jQuery 1.3

    $("textarea[maxlength]").keypress(function(event){
    		var key = event.which;
    
    		//all keys including return.
    		if(key &gt;= 33 || key == 13) {
    			var maxLength = $(this).attr("maxlength");
    			var length = this.value.length;
    			if(length == maxLength) {
    				event.preventDefault();
    				$("#error_field").html('Maximum length is 120 characters.');				
    			}		
    		}
    	});
    

  20. Max says:

    Hi
    Here’s another way to do it.
    http://www.problemquestionsolution.com/View/JavaScript/Textarea-maxlength

  21. Murali says:

    Please have a look into this

    http://that-matt.com/2010/04/updated-textarea-maxlength-with-jquery-plugin/

  22. Deepak says:

    wont work for below text….. :(

    ああsだどいういえrをるおいうこくおいううぇryをりyをれyをりょしよzxcyぞこいいぇろうぇいryをyを得rwいぇおryをえryをえryをえりょああだづいういあしあいやいしゃいsyぢあぢぃあsぢぃあぢゃいぢゃいうぢゃいうぢゃいうぢゃいうぢゃいづやsぢうあyぢあyぢあぢぃあぢゃいうぢゃいうぢゃいづやいうぢゃいうぢゃいうsぢゃ位末dチャイウェ地亜謝意やいうえやいうえりぃえとぃryうぇいrywりwyりうwいぇりwryうぃえうryうぃryうぃえる

    any suggestion will be appreciated…. thanks in advance…

  23. GFoley83 says:

    Updated version for jQuery 1.3+ which also includes text boxes and prevents spaces in IE.

    jQuery.fn.maxlength = function(){ 
        $('textarea[maxlength], input[maxlength]').keypress(function(event){
            var key = event.which; 
            //all keys including return and space.
            if(key &gt;= 32 || key == 13) {
                var maxLength = $(this).attr('maxlength');
                var length = this.value.length;
                if(length &gt;= maxLength) { 
                    event.preventDefault();
                }
            }
        });
    }
    

  24. mike says:

    Do you know how to deal if they copy from cliboard data your Jquery code doesn’t handle it.
    Thanks

  25. David says:

    hi, sorry it can’t work

  26. David says:

    below is my code,please help me, it can’t work

    Maxlength Textbox jQuery Plugin

    jQuery(document).ready(function($) {
    //Set maxlength of all the textarea (call plugin)
    $().maxlength();
    })

    Maxlength 20

    Maxlength 50

    No Maxlength

  27. chandan says:

    not working when placing space instead of any text

  28. Jazz says:

    you can use this instead of the jquery plugin, works great:

    add this javascript function on a script section or an include file:

    function ismaxlength(obj)
    {
    var mlength=obj.getAttribute? parseInt(obj.getAttribute(“maxlength”)) : “”
    if (obj.getAttribute && obj.value.length>mlength)
    obj.value=obj.value.substring(0,mlength)
    }

    then, when you define your textarea:

    that’s it, it works with copy/paste, spaces, anything.

    • Jazz says:

      this is how you define the textarea:

      <textarea id='OriginalContent' name='OriginalContent' class='form' rows='5' cols='70' maxlength='5' onkeyup='return ismaxlength(this);'></textarea>
      

  29. dany says:

    there is crash with another plugin jquery..

  30. Darshana Umakanth says:

    Thanks, Viral! Worked like a charm :)

  31. Bharat says:

    Thanks Viral. I am trying to use this plugin with struts2 tag s:textarea but haven’t succeeded yet. Do you know if this works with strats2 tag library tag ?

  32. Venu says:

    How can we include this pluggin code into another JS file or can we do it liek that…?

  33. Christopher Roldan says:

    Where in the theme do you input the code in? I’m a “newbie” to this and any help would be great! Thanks everyone

  34. dupia says:

    hi,
    i’m working on mobile app…(using jquey mobile ) below is my code for textarea

    if i open this in IE Browser, it doesnot show its actual size.
    can you pls help me on this

Leave a Reply

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