textArea不支持“ maxlength ”属性,但是您可以使用JavaScript动态限制textArea的长度。
HTML 5
HTML 5支持textArea“ maxlength ”属性,并不是所有浏览器都支持HTML 5,尤其是旧的IE。
jQuery示例
一个在textarea字段上实现“ maxlength ”效果的jQuery示例。
<html>
<head>
<script language="javascript" type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
$(document).ready( function () {
maxLength = $("textarea#comment").attr("maxlength");
$("textarea#comment").after("<div><span id='remainingLengthTempId'>"
+ maxLength + "</span> remaining</div>");
$("textarea#comment").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#comment").val($("textarea#comment").val().slice(0, maxLength));
$(remainingLengthTempId).text(0);
}
}
</script>
</head>
<body>
<h1>TextArea maxlength with jQuery</h1>
<textarea id="comment" maxlength="10" rows="10" cols="60" ></textarea>
</body>
</html>
演示版
翻译自: https://mkyong.com/jquery/add-maxlength-on-textarea-using-jquery/