jQuery文本域最大长度验证

5
我有以下代码,它运行良好,但问题是在超过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");
           }
       });"

我一直以为只有输入类型才能接受maxlength? - JonH
@JonH,这就是为什么他想要为textarea做这件事的原因。 - Amir Raminfar
你能发一下相关的HTML吗? - Sparky
显示剩余3条评论
3个回答

8

你不应该在 keyup 上绑定事件。请尝试使用 keypress。问题在于 keyup 触发时,字符已经被写入到文本区域中。这是一个很好的教程,请注意其中的 keypress 事件。

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

});

keydown 生效了,但有没有办法将上述方法泛化,以便我可以将其用于多个文本框? - Tan
1
@Tan,发布了一些适用于所有浏览器的内容。请注意,在Opera浏览器中,只允许使用keypress来取消操作,而keydown无法生效。希望这能有所帮助。请查看教程以获取更多帮助。 - Amir Raminfar
1
这很好,但“13”不应该是一个要忽略的键。 这允许您输入无限数量的回车符。我认为“最大长度”包括回车/换行符。 - mhenry1384

6

您可以尝试定义一个用于比较的maxLength(如果未定义,则等于undefined,每个数字都大于undefined:这就是为什么我认为您从未收到警报的原因):

$('#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");
           }
       });"

这不是一个好的解决方案,因为在某些浏览器上 $(this).val(...) 会移动光标。 - Amir Raminfar

0

解决方案有两个方面:

  • 使用 keydown 事件而不是 keyup 来捕获字母插入之前的事件
  • 使用 preventDefault 阻止字母被插入

    $('#txtAboutMe').keyup(function (e) {//注意添加 e 以传递事件数据
       var text = $(this).val();
       var textLength = text.length;`enter code here`
       if (text.length > maxLength) {
           $(this).val(text.substring(0, (maxLength)));
           alert("抱歉,只允许输入 " + maxLength + " 个字符");
           e.preventDefault();
           return;
       }
       else {
           //alert("必须至少输入 500 个字符");
       }
    

    });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接