5

I have the following code which works well, but the problem is that after exceeding the 500 characters it starts to allow the user to type (it accepts the characters instead of restricting them!).

How can I modify it? Is there any possibility to generalize this code so it can handle multiple text areas, like a function and just pass the parameters?

 $('#txtAboutMe').keyup(function () {
           var text = $(this).val();
           var textLength = text.length;`enter code here`
           if (text.length > maxLength) {
               $(this).val(text.substring(0, (maxLength)));
               alert("Sorry, you only " + maxLength + " characters are allowed");
           }
           else {
               //alert("Required Min. 500 characters");
           }
       });"
Mahdi Alkhatib
  • 1,954
  • 1
  • 29
  • 43
Tan
  • 778
  • 3
  • 18
  • 36
  • I always thought only input types would accept a maxlength ? – JonH Jul 29 '11 at 18:38
  • @JonH, that's why he wants to do it for textarea – Amir Raminfar Jul 29 '11 at 18:40
  • Can you post the relevant HTML? – Sparky Jul 29 '11 at 18:40
  • @Amir but searching stackoverflow there are plenty of jquery solutions fo this. – JonH Jul 29 '11 at 18:40
  • yes u are right textarea is a input type only – Tan Jul 29 '11 at 18:40
  • possible duplicate of [How to impose maxlength on textArea in HTML using JavaScript](http://stackoverflow.com/questions/1125482/how-to-impose-maxlength-on-textarea-in-html-using-javascript) – JonH Jul 29 '11 at 18:40
  • Try this: [This solution is working as native HTML text-area , MAX-Length property ][1] [1]: http://stackoverflow.com/questions/15031513/jquery-help-to-enforce-maxlength-on-textarea/25678003#25678003 – VoidA313 Sep 05 '14 at 02:59
  • Try this: [This solution is working as native HTML text-area , MAX-Length property ][1] [1]: http://stackoverflow.com/questions/15031513/jquery-help-to-enforce-maxlength-on-textarea/25678003#25678003 – VoidA313 Sep 05 '14 at 04:56

3 Answers3

8

You shouldn't do on keyup. Try keypress instead. The problem is on keyup the character has already been triggered and written to textarea. Here is a good tutorial. Notice the keypress event.

jQuery(function($) {

  // ignore these keys
  var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];

  // use keypress instead of keydown as that's the only
  // place keystrokes could be canceled in Opera
  var eventName = 'keypress';

  // handle textareas with maxlength attribute
  $('textarea[maxlength]')

    // this is where the magic happens
    .live(eventName, function(event) {
      var self = $(this),
          maxlength = self.attr('maxlength'),
          code = $.data(this, 'keycode');

      // check if maxlength has a value.
      // The value must be greater than 0
      if (maxlength && maxlength > 0) {

        // continue with this keystroke if maxlength
        // not reached or one of the ignored keys were pressed.
        return ( self.val().length < maxlength
                 || $.inArray(code, ignore) !== -1 );

      }
    })

    // store keyCode from keydown event for later use
    .live('keydown', function(event) {
      $.data(this, 'keycode', event.keyCode || event.which);
    });

});
Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
  • keydown worked but is there any way to generalise the above method so that i can use it for multiple textboxes – Tan Jul 29 '11 at 18:45
  • 1
    @Tan, posted something you can use for all browsers. Note on opera only keypress is allowed to cancel and keydown doesn't work. Hopefully this helped. Check out the tutorial for more help. – Amir Raminfar Jul 29 '11 at 18:47
  • 1
    This is great, but "13" shouldn't be a key to ignore. That allows you to enter an infinite number of carriage returns. I would expect that "max length" includes carriage return/line feeds. – mhenry1384 Jan 18 '13 at 20:58
6

You could try defining a maxLength to be used for comparing (if it's not defined is equal to undefined and every number is more than undefined: that's why you nevere get the alert i think):

$('#txtAboutMe').keyup(function () {
           var maxLength = 500;
           var text = $(this).val();
           var textLength = text.length;
           if (textLength > maxLength) {
               $(this).val(text.substring(0, (maxLength)));
               alert("Sorry, you only " + maxLength + " characters are allowed");
           }
           else {
               //alert("Required Min. 500 characters");
           }
       });"
K.C.
  • 2,084
  • 2
  • 25
  • 38
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
0

The solution is two fold:

  • use keydown event instead of keyup to catch the event before the letter is inserted
  • use preventDefault to stop the letter from being inserted

    $('#txtAboutMe').keyup(function (e) {//note the added e to pass the event data
       var text = $(this).val();
       var textLength = text.length;`enter code here`
       if (text.length > maxLength) {
           $(this).val(text.substring(0, (maxLength)));
           alert("Sorry, you only " + maxLength + " characters are allowed");
           e.preventDefault();
           return;
       }
       else {
           //alert("Required Min. 500 characters");
       }
    

    });