Jquery有助于在textarea上强制执行maxlength?

这是Jquery在添加属性“maxlength”时强制执行textarea的maxlength。 IE不支持Maxlength。 如何调整我的代码以处理页面上的多个textarea? 目前,如果我向任何textarea添加文本,它们都会倒计时具有相同的值。

jQuery的:

$(document).ready( function () { maxLength = $("textarea").attr("maxlength"); $("textarea").after("
" + maxLength + " remaining
"); $("textarea").bind("keyup change", function(){checkMaxLength(this.id, maxLength); } ) }); function checkMaxLength(textareaID, maxLength){ currentLengthInTextarea = $("#"+textareaID).val().length; $(remainingLengthTempId).text(parseInt(maxLength) - parseInt(currentLengthInTextarea)); if (currentLengthInTextarea > (maxLength)) { // Trim the field current length over the maxlength. $("textarea").val($("textarea").val().slice(0, maxLength)); $(remainingLengthTempId).text(0); } }

HTML:

 Skills:  Postions:  Comments  

这是最好的解决方案! 将其放入HTML代码中的脚本标记中

 $("textarea[maxlength]").on("propertychange input", function() { if (this.value.length > this.maxlength) { this.value = this.value.substring(0, this.maxlength); } }); 

现在使用作为{your limit} chars limit。

解决方案在这里:

http://web.enavu.com/daily-tip/maxlength-for-textarea-with-jquery/

 $(document).ready(function() { $('textarea[maxlength]').keyup(function(){ //get the limit from maxlength attribute var limit = parseInt($(this).attr('maxlength')); //get the current text inside the textarea var text = $(this).val(); //count the number of characters in the text var chars = text.length; //check if there are more characters then allowed if(chars > limit){ //and if there are use substr to get the text before the limit var new_text = text.substr(0, limit); //and change the current text with the new text $(this).val(new_text); } }); }); 

不能用这个:

  class="validate[required,maxSize[50]] " 

此解决方案用作本机HTML文本区域,MAX-Length属性

 Var MaxLength=100; $('#Selector').keydown(function (e) { var text = $(this).val(); var chars = text.length; if (chars > MaxLength) { if (e.keyCode == 46 || e.keyCode == 8 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40) { return true; } return false; } return true; }); 

不要在服务器端控件(asp:TextBox)中设置Maxlength属性,因为服务器在返回浏览器时不会将maxLength属性转换为HTML标记。