2010-09-02 67 views
0

我想阻止用戶輸入超過100個字符到textarea。我已經編寫了能夠檢測用戶帖子達到100個字符的代碼。但我不知道如何防止他打字超過這一點:如何防止用戶使用JQuery將文本輸入到表單字段中?

$(document).ready(function(){ 

    $('.comment').keyup(function(){ 
     var count = this.value.length; 
     if (count > 100) { 

      // what goes here??? 

     }   
    }); 

}); 


    <textarea class="comment" rows="10" cols="30"></textarea> 
+0

做你應該有這個服務器端驗證過,明明:d – 2010-09-02 01:38:16

+0

@CrazyJugglerDrummer總是。 – 2010-09-02 01:40:00

+2

如果你按住keyyyyyyyyyyyyyyyyyyyyyyyyyy? – robotdana 2010-09-02 02:07:13

回答

3

使用keypress可能會更好。你可以只return false;

​$('textarea').keypress(function() { 
    if(this.value.length >= 100) 
     return false; 
})​​​​​;​ 

這也阻止用戶按住一個按鍵來進入幾個字符超越極限。

如果你想使用keyup,你可以這樣做:

$('.comment').keyup(function(){ 
    var count = this.value.length; 
    if (count > 100) { 

    this.value = this.value.substr(0,100); 

    }   
}); 
0
$(document).ready(function(){ 
    $('textarea[maxlength]').keyup(function(){ 
     var max = parseInt($(this).attr(’maxlength’)); 
     if($(this).val().length > max){ 
      $(this).val($(this).val().substr(0, $(this).attr('maxlength'))); 
     } 

     $(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining'); 
    }); 
}); 

http://that-matt.com/2008/07/textarea-maxlength-with-jquery/

也有這個http://remysharp.com/2008/06/30/maxlength-plugin/

1
​jQuery('textarea').keypress(function(e) { 
    if(this.value.length >= 100) { 
     e.preventDefault(); 
     return false; 
    } 
})​​​​​;​ 

的preventDefault插件需要對於像IE這樣的瀏覽器和所有的支持; 但實際上只需要一個HREF的onclick

KEYUP是不是爲了防止鍵好的活動...鍵重複用的keydown

相關問題