22

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

Firdous
  • 4,624
  • 13
  • 41
  • 80

9 Answers9

51

make use of maxlength in input tag

<input type="text" maxlength="20" /> 
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
22

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

<input class="test-input" type="text" maxlength="12" />
<script>
$('.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');
    if(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
}); 
</script>

http://jsfiddle.net/tvpRT/

Serg Hospodarets
  • 4,658
  • 4
  • 25
  • 31
  • very nice, except you used an "input" instead of a div contenteditable :) – Raphael Jeger May 13 '13 at 09:18
  • 2
    ...probably because not all browsers support content editable... Sergey's answer is the best one here :) – Rob Jan 02 '14 at 23:41
  • Shouldnt this be `$this.val($this.val().substring(0,maxCount-1));` to account for substring starting at 0? Correct me if im wrong please. And yes, this is an old thread, but still read by people. – redfox05 Nov 17 '14 at 13:12
9

This should work for you I think.

HTML

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

jQuery

$('#myText').keyup(validateMaxLength);

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

        if(maxlength > 0)  
        {
                $(this).val(text.substr(0, maxlength)); 
        }
}
JF Paris
  • 134
  • 4
6

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.

Jules
  • 7,148
  • 6
  • 26
  • 50
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)) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
            });

            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

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
4

Let's say it is form input.
you can do it with 'maxlength' attribute but if you say 'using jQuery',
here's the solution.

$('input#limited').attr('maxlength', '3'); 

or you can check every keypress

$('input#limited').keypress(function() {
     /*
     check for 3 or greater than 3 characters.
     If you check for only greater than 3, then it will let
     you write the fourth character because just before writing,
     it is not greater than three.
     */
     if($(this).val().length >= 3) {
        $(this).val($(this).val().slice(0, 3));
        return false;
    }
});
Dave Everitt
  • 17,193
  • 6
  • 67
  • 97
Sang
  • 2,790
  • 2
  • 20
  • 17
2
$('#id').keypress(function(e) {
   var foo = $(this).val()
   if (foo.length >= 14) { //specify text limit
     return false;
   }
   return true;
});
ask me
  • 3
  • 4
Hafsal Rh
  • 191
  • 1
  • 3
  • What exactly is the point in returning either `true` or `false`? Why should one use JS for this if the browser supports other ways? – Nico Haase May 07 '19 at 07:45
  • 1
    after 14 characters that returns false, afterwards user can't input value. js is a convenient way to this. – Hafsal Rh May 07 '19 at 09:04
0
<input type="text" maxlength="20" id="alert_title"/>
$('#alert_title').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');
        if(typeof maxCount == "undefined"){
            $this.attr('maxlength',100);
        }
        if(valLength>maxCount){
            $this.val($this.val().substring(0,maxCount));
        }
    }); 
ask me
  • 3
  • 4
0

just use attribute called "maxlength". You can read more about input's attributes at w3 input

mkk
  • 7,583
  • 7
  • 46
  • 62