jQuery文本区域最大长度验证

时间:2011-07-29 18:36:27

标签: 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");
           }
       });"

3 个答案:

答案 0 :(得分:8)

你不应该keyup。请尝试使用keypress。问题是在keyup上,角色已被触发并写入textarea。这是一个很好的tutorial。注意按键事件。

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

});

答案 1 :(得分:5)

您可以尝试定义一个用于比较的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");
           }
       });"

答案 2 :(得分:0)

解决方案有两个方面:

  • 使用keydown事件代替keyup来在插入字母之前捕获事件
  • 使用preventDefault来阻止插入字母

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

    });

相关问题