Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery text area max length validation

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");
           }
       });"
like image 565
Tan Avatar asked Dec 10 '22 07:12

Tan


1 Answers

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

});
like image 166
Amir Raminfar Avatar answered Dec 31 '22 16:12

Amir Raminfar