jQuery帮助在textarea上强制使用maxlength吗? [英] Jquery help to enforce maxlength on textarea?
本文介绍了jQuery帮助在textarea上强制使用maxlength吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当添加属性"maxlength"时,这是Jquery强制textarea的maxlength. IE不支持Maxlength.如何调整代码以处理页面上的多个文本区域?目前 如果我将文本添加到任何文本区域,它们都将以相同的值倒计时.
Here is Jquery to enforce maxlength for textarea when you add the attribute "maxlength". Maxlength is not supported with IE. How do I adjust my code to handle multiple textarea(s) on the page? Currently if I add text to any textarea, they all countdown with the same value.
jQuery:
$(document).ready( function () {
maxLength = $("textarea").attr("maxlength");
$("textarea").after("<div><span id='remainingLengthTempId'>"
+ maxLength + "</span> remaining</div>");
$("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:
<textarea id="1" maxlength="200" rows="10" cols="60" ></textarea>
Postions:
<textarea id="2" maxlength="200" rows="10" cols="60" ></textarea>
Comments
<textarea id="3" maxlength="100" rows="10" cols="60" ></textarea>
推荐答案
这是最好的解决方案! 将其放入HTML代码中的脚本标签中
This is the best solution! Put this into your script tag in HTML code
$("textarea[maxlength]").on("propertychange input", function() {
if (this.value.length > this.maxlength) {
this.value = this.value.substring(0, this.maxlength);
}
});
,现在将<textarea maxlength="{your limit}"></textarea>
用于{your limit}
字符数限制.
and now use <textarea maxlength="{your limit}"></textarea>
for {your limit}
chars limit.
这篇关于jQuery帮助在textarea上强制使用maxlength吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文