How to prevent user to enter text in textarea after reaching max character limit

Solution 1:

The keyup event fires after the default behaviour (populating text area) has occurred.

It's better to use the keypress event, and filter non-printable characters.

Demo: http://jsfiddle.net/3uhNP/1/ (with max length 4)

jQuery(document).ready(function($) {
    var max = 400;
    $('textarea.max').keypress(function(e) {
        if (e.which < 0x20) {
            // e.which < 0x20, then it's not a printable character
            // e.which === 0 - Not a character
            return;     // Do nothing
        }
        if (this.value.length == max) {
            e.preventDefault();
        } else if (this.value.length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
    });
}); //end if ready(fn)

Solution 2:

<textarea maxlength="400"> </textarea>

Use the above code to limit the number of characters inserted in a text area, if you want to disable the textarea itself (ie, will not be able to edit afterwards) you can use javascript/jquery to disable it.

Solution 3:

Keep it simple

var max = 50;
$("#textarea").keyup(function(e){
$("#count").text("Characters left: " + (max - $(this).val().length));
});

and add this in your html

<textarea id="textarea" maxlength="50"></textarea>
<div id="count"></div>

view example

Solution 4:

Just write this code in your Javascript file.. But Need to specify the 'maxlength' attribute with textarea. This will work for all textarea of a page.

$('textarea').bind("change keyup input",function() {

        var limitNum=$(this).attr("maxlength");

        if ($(this).val().length > limitNum) {
            $(this).val($(this).val().substring(0, limitNum));
        }

    });

Solution 5:

You could directly give maxlength to textarea to disable itself. But, you want to showing appropriate message then use keyup event for default behavior and textarea length for calculating charcter and display suitable message.

HTML

<div id="count"></div>
<textarea class="max"  maxlength="250" id="tarea"></textarea>
<div id="msg"></div>

jQuery

$(function(){
    var max = parseInt($("#tarea").attr("maxlength"));
  $("#count").text("Characters left: " + max);
    $("#tarea").keyup(function(e){
        $("#count").text("Characters left: " + (max - $(this).val().length));
    if($(this).val().length==max)
        $("#msg").text("Limit Reached....");
        else
        $("#msg").text("");
    });
});

Demo Fiddle