How to:Set Maxlength of Textarea using jQuery/JavaScript

      

Maxlength of Textarea

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>

Include the jQuery plugin javascript file in your html page where the textarea is.

<script language="javascript" src="jquery.maxlength.js"></script>

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>

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

/*
 *
 * Textarea Maxlength Setter JQuery Plugin
 * Version 1.0
 *
 * Copyright (c) 2008 Viral Patel
 * website : http://viralpatel.net/blogs
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
*/
jQuery.fn.maxlength = function(){

	$("textarea[@maxlength]").keypress(function(event){
		var key = event.which;

		//all keys including return.
		if(key >= 33 || key == 13) {
			var maxLength = $(this).attr("maxlength");
			var length = this.value.length;
			if(length >= maxLength) {

				event.preventDefault();
			}
		}
	});
}

Demo

Download

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.


Facebook  Twitter      Stumbleupon  Delicious
  

20 Comments on “How to:Set Maxlength of Textarea using jQuery/JavaScript”

  • gaurav wrote on 19 December, 2008, 14:31

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

  • webcook wrote on 21 January, 2009, 17:57

    hi viral
    great job thanks :D

  • Viral wrote on 21 January, 2009, 18:51

    Thanks Webcook for the comment. :)

  • M12 G12 Visão Celular wrote on 24 January, 2009, 1:03

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

  • SS wrote on 26 March, 2009, 19:17

    Good Code. But not handled the paste situation

  • Suji wrote on 31 March, 2009, 12:22

    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)\"

  • Juanpe wrote on 1 April, 2009, 6:17

    And the space key?

  • Breaking News wrote on 6 April, 2009, 19:26

    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.

  • Anthony wrote on 8 April, 2009, 13:59

    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.

  • Victor wrote on 14 May, 2009, 18:52

    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;
    }
    }

  • ZK@Web Marketing Blog wrote on 21 June, 2009, 10:36

    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

  • Dave wrote on 6 August, 2009, 23:11

    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.

  • Andrea wrote on 13 August, 2009, 15:14

    Does not work with COPY/PASTE.

  • Akash Bavlecha wrote on 10 November, 2009, 15:00

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

  • thomasp wrote on 8 December, 2009, 14:25

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

  • BenTheTipsyBear wrote on 13 February, 2010, 3:22

    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!

  • BenTheTipsyBear wrote on 13 February, 2010, 3:32

    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!

  • Gurinder wrote on 22 February, 2010, 5:20

    Try pasting a long text , This plugin will fail.

  • Viral Patel wrote on 23 February, 2010, 15:50

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

  • Zachary Burt wrote on 26 February, 2010, 4:13

    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.');
    			}
    		}
    	});
    

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.