jQuery文本区域最大长度验证

Tan*_*Tan 4 jquery textarea maxlength

我有以下代码,它运行良好,但问题是,超过500个字符后,它开始允许用户键入(它接受字符而不是限制它们!).

我怎么修改它?有没有可能推广这个代码,以便它可以处理多个文本区域,如一个函数,只是传递参数?

 $('#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");
           }
       });"
Run Code Online (Sandbox Code Playgroud)

Ami*_*far 8

你不应该这样做keyup.试试吧keypress.问题在于keyup角色已被触发并写入textarea.这是一个很好的教程.注意按键事件.

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

});
Run Code Online (Sandbox Code Playgroud)


Nic*_*tti 6

您可以尝试定义一个用于比较的maxLength(如果它未定义等于未定义且每个数字都超过未定义:这就是为什么你会得到我认为的警报):

$('#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");
           }
       });"
Run Code Online (Sandbox Code Playgroud)