How to impose maxlength on textArea in HTML using JavaScript

JavascriptHtmlTextarea

Javascript Problem Overview


I would like to have some functionality by which if I write

<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>

it will automatically impose the maxlength on the textArea. If possible please do not provide the solution in jQuery.

Note: This can be done if I do something like this:

<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">

function imposeMaxLength(Event, Object, MaxLen)
{
    return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}

Copied from What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?

But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.

Javascript Solutions


Solution 1 - Javascript

window.onload = function() { 
  var txts = document.getElementsByTagName('TEXTAREA'); 
 
  for(var i = 0, l = txts.length; i < l; i++) {
    if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) { 
      var func = function() { 
        var len = parseInt(this.getAttribute("maxlength"), 10); 

        if(this.value.length > len) { 
          alert('Maximum length exceeded: ' + len); 
          this.value = this.value.substr(0, len); 
          return false; 
        } 
      }

      txts[i].onkeyup = func;
      txts[i].onblur = func;
    } 
  };

}

Solution 2 - Javascript

I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust.

Inspired by, but an improvement over Dana Woodman's answer:

Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE):

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

EDIT: Updated version for jQuery 1.7+, using on instead of live

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

Solution 3 - Javascript

Update Use Eirik's solution using .live() instead as it is a bit more robust.


Even though you wanted a solution that wasn't using jQuery, I thought I'd add one in for anyone finding this page via Google and looking for a jQuery-esque solution:

$(function() {        
    // Get all textareas that have a "maxlength" property.
    $('textarea[maxlength]').each(function() {
        
        // Store the jQuery object to be more efficient...
        var $textarea = $(this);
        
        // Store the maxlength and value of the field.
        var maxlength = $textarea.attr('maxlength');
        var val = $textarea.val();

        // Trim the field if it has content over the maxlength.
        $textarea.val(val.slice(0, maxlength));

        // Bind the trimming behavior to the "keyup" event.
        $textarea.bind('keyup', function() {
            $textarea.val($textarea.val().slice(0, maxlength));
        });

    });
});

Hope that is useful to you Googlers out there...

Solution 4 - Javascript

HTML5 adds a maxlength attribute to the textarea element, like so:

<!DOCTYPE html>
<html>
    <body>
        <form action="processForm.php" action="post">
            <label for="story">Tell me your story:</label><br>
            <textarea id="story" maxlength="100"></textarea>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

This is currently supported in Chrome 13, FF 5, and Safari 5. Not surprisingly, this is not supported in IE 9. (Tested on Win 7)

Solution 5 - Javascript

This solution avoids the issue in IE where the last character is removed when a character in the middle of the text is added. It also works fine with other browsers.

$("textarea[maxlength]").keydown( function(e) {
    var key = e.which;  // backspace = 8, delete = 46, arrows = 37,38,39,40

    if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;

    return $(this).val().length < $(this).attr( "maxlength" );
});

My form validation then deals with any issues where the user may have pasted (only seems to be a problem in IE) text exceeding the maximum length of the textarea.

Solution 6 - Javascript

This is some tweaked code I've just been using on my site. It is improved to display the number of remaining characters to the user.

(Sorry again to OP who requested no jQuery. But seriously, who doesn't use jQuery these days?)

$(function() {
	// Get all textareas that have a "maxlength" property.
	$("textarea[maxlength]").each(function() {

		// Store the jQuery object to be more efficient...
		var $textarea = $(this);

		// Store the maxlength and value of the field
		var maxlength = $textarea.attr("maxlength");

		// Add a DIV to display remaining characters to user
		$textarea.after($("<div>").addClass("charsRemaining"));
		
		// Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
		$textarea.on("keyup blur", function(event) {
			// Fix OS-specific line-returns to do an accurate count
			var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
			$textarea.val(val);
			// Display updated count to user
			$textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
		}).trigger("blur");

	});
});

Has NOT been tested with international multi-byte characters, so I'm not sure how it works with those exactly.

Solution 7 - Javascript

Also add the following event to deal with pasting into the textarea:

...

txts[i].onkeyup = function() {
  ...
}

txts[i].paste = function() {
  var len = parseInt(this.getAttribute("maxlength"), 10);

  if (this.value.length + window.clipboardData.getData("Text").length > len) {
    alert('Maximum length exceeded: ' + len);
    this.value = this.value.substr(0, len);
    return false;
  }
}

...

Solution 8 - Javascript

Solution 9 - Javascript

You can use jQuery to make it easy and clear

JSFiddle DEMO

<textarea id="ta" max="10"></textarea>

<script>
$("#ta").keypress(function(e){

    var k = e.which==0 ? e.keyCode : e.which;
    //alert(k);
    if(k==8 || k==37 || k==39 || k==46) return true;
	
	var text      = $(this).val();
	var maxlength = $(this).attr("max");
	
	if(text.length >= maxlength) {
		return false;	
	}
	return true;
});
</script>

It is tested in Firefox, Google Chrome and Opera

Solution 10 - Javascript

Better Solution compared to trimming the value of the textarea.

$('textarea[maxlength]').live('keypress', function(e) {
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    if (val.length > maxlength) {
    	return false;
    }
});

Solution 11 - Javascript

Small problem with code above is that val() does not trigger change() event, so if you using backbone.js (or another frameworks for model binding), model won't be updated.

I'm posting the solution worked great for me.

$(function () {

	$(document).on('keyup', '.ie8 textarea[maxlength], .ie9 textarea[maxlength]', function (e) {
		var maxLength = $(this).attr('maxlength');
		if (e.keyCode > 47 && $(this).val().length >= maxLength) {
			$(this).val($(this).val().substring(0, maxLength)).trigger('change');
		}
		return true;
	});

});

Solution 12 - Javascript

I implemented maxlength behaviour on textarea recently, and run into problem described in this question: https://stackoverflow.com/questions/10030921/chrome-counts-characters-wrong-in-textarea-with-maxlength-attribute.

So all implementations listed here will work little buggy. To solve this issue I add .replace(/(\r\n|\n|\r)/g, "11") before .length. And kept it in mind when cuting string.

I ended with something like this:

var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
    el.val(val.slice(0, maxlength - (realLength - length)));
}

Don't sure if it solves problem completely, but it works for me for now.

Solution 13 - Javascript

Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:

$("#comments").bind("keyup keydown", function() {
	var max = 500;
	var value = $(this).val();
	var left = max - value.length;
	if(left < 0) {
		$(this).val( value.slice(0, left) );
		left = 0;
	}
	$("#charcount").text(left);
});	

<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>

Solution 14 - Javascript

Try to use this code example:

$("#TextAreaID1").bind('input propertychange', function () {
    var maxLength = 4000;
    if ($(this).val().length > maxLength) {
        $(this).val($(this).val().substring(0, maxLength));
    }
});

Solution 15 - Javascript

This is much easier:

<textarea onKeyPress="return ( this.value.length < 1000 );"></textarea>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRakesh JuyalView Question on Stackoverflow
Solution 1 - JavascriptJosh StodolaView Answer on Stackoverflow
Solution 2 - JavascriptEirik WView Answer on Stackoverflow
Solution 3 - JavascriptDana WoodmanView Answer on Stackoverflow
Solution 4 - Javascriptjames.garrissView Answer on Stackoverflow
Solution 5 - JavascriptChris RView Answer on Stackoverflow
Solution 6 - JavascriptSimon EastView Answer on Stackoverflow
Solution 7 - JavascriptstusherwinView Answer on Stackoverflow
Solution 8 - JavascriptEasonView Answer on Stackoverflow
Solution 9 - JavascriptMaxEchoView Answer on Stackoverflow
Solution 10 - JavascriptBharatView Answer on Stackoverflow
Solution 11 - JavascriptAlexander BeletskyView Answer on Stackoverflow
Solution 12 - JavascriptRoman PominovView Answer on Stackoverflow
Solution 13 - JavascriptLeslie KingView Answer on Stackoverflow
Solution 14 - JavascriptnaveenView Answer on Stackoverflow
Solution 15 - JavascripterdomesterView Answer on Stackoverflow