Textarea maxlength检查

Textareavalidation,

如何限制textarea的字符不超过50个字符。

  

谢谢…..

一个谷歌远。

  Implementation:  

编辑:

不冻结文本的代码:

   

使用:

  

来自http://sigswitch.com/2008/07/textarea-maxlength-with-jquery/ :

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

更简单的内联方法:

  

将“100”更改为您想要的多个字符

  function checkTextAreaMaxLength(textBox, e, maxLength) { if (!checkSpecialKeys(e)) { if (textBox.value.length > maxLength - 1) { if (window.event)//IE e.returnValue = false; else//Firefox e.preventDefault(); } } onBlurTextCounter(textBox, maxLength); } function checkSpecialKeys(e) { if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40) return false; else return true; } function onBlurTextCounter(textBox, maxLength) { if (textBox.value.length > maxLength) textBox.value = textBox.value.substr(0, maxLength); } 

我不知道内置的HTML方式,但你可以使用这个:

 ​​​​​​​​​​​​​​ function validateCharLimit(area) { var limit = 50; var iChars = area.value.length; if (iChars > limit) { return false; } return true; } 
     

使用jQuery限制TextArea中的字符数

    Limit Number of Characters in a TextArea     
(Maximum characters: 50)
Characters left

这是一个利用HTML 5 textarea的“maxLength”属性和jQuery 1.7+的解决方案。

1.将“maxLength”属性添加到textarea

  

2.为textarea添加jQuery事件处理程序

 $(function() { $('#myTextArea').on('input propertychange', function () { var propMaxLength = $(this).prop('maxLength'); if (!propMaxLength || typeof propMaxLength != 'number') { var maxLength = $(this).attr('maxlength'), txt = $(this).val(); if (txt.length > maxLength) { $(this).val(txt.substr(0, maxLength)); } } }); });