jquery - tag - Limit number of characters in input field

textarea default character limit (5)

As for input field you can use maxlength attribute. If you are looking for div, check the following,

        $(function() {

            $ ('#editable_div').keydown ( function (e) {
                //list of functional/control keys that you want to allow always
                var keys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];

                if( $.inArray(e.keyCode, keys) == -1) {
                    if (checkMaxLength (this.innerHTML, 15)) {

            function checkMaxLength (text, max) {
                return (text.length >= max);

        <div id="editable_div" contentEditable="true" onclick="this.contentEditable='true';" >TEXT BEGIN:</div>

Edit: you should rewrite the checkMaxLength function to ignore tabs and newline

I want to use jquery to limit the number of characters in an editable div (or form input).

If you want to make use of JQuery you can write something yourself or just use an existing plugin such as this one.

But I agree with dku.rajkumar... What is wrong with using the maxlength attribute?

<input type="text" maxlength="15" />

If you're the biggest JQuery fan ever though and desperately want to set a maxlength to all of the input fields at once do something like:

$(document).ready(function() {
   $('input[type="text"]').attr({ maxLength : 15 });

Just keep in mind though that this method (the JQuery one) will not work for people who have (for any reason whatsoever) JavaScript disabled. While the maxlength attribute of the input tag works for everybody on all browsers.

Maxlength attribute- for browser, that support this feature.
Javascript - for others.

<input class="test-input" type="text" maxlength="12" />
$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
    var $this = $(this);
    var val = $this.val();
    var valLength = val.length;
    var maxCount = $this.attr('maxlength');


This should work for you I think.


<input type="text" name="myText" id="myText" data-maxlength="10" />



function validateMaxLength()
        var text = $(this).val();
        var maxlength = $(this).data('maxlength');

        if(maxlength > 0)  
                $(this).val(text.substr(0, maxlength)); 

make use of maxlength in input tag

<input type="text" maxlength="20" />