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

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)

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


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


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

    });

Tags:

Jquery