4

私はうまく機能する次のコードを持っていますが、問題は、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");
           }
       });"
4

3 に答える 3

8

してはいけませんkeyupkeypress代わりに試してください。問題は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);
    });

});
于 2011-07-29T18:41:10.057 に答える
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");
           }
       });"
于 2011-07-29T18:46:02.943 に答える
0

解決策は 2 つあります。

  • keyup の代わりに keydown イベントを使用して、文字が挿入される前にイベントをキャッチします
  • 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");
       }
    

    });

于 2013-10-25T04:55:10.213 に答える