使用js实现textarea文本域长度,限制输入字数并统计剩余输入字符数
输入框

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function getStringUTFLength(str) {
var value = str.replace(/[^\x00-\xff]/g, " ");
return value.length;
}
function leftUTFString(str, len) {
if (getStringUTFLength(str) <= len)
return str;
var value = str.substring(0, len);
while (getStringUTFLength(value) > len) {
value = value.substring(0, value.length - 1);
}
return value;
}
function count() {
var value = document.getElementById("licenseother").value;
value = value.replace(/[\u4e00-\u9fa5]/g, " ");
if (value.length >= 255) {
with (window.event) {
cancelBubble = true;
keyCode = 0;
returnValue = false;
}
document.getElementById("licenseother").value = leftUTFString(document.getElementById("licenseother").value, 8);
}
document.getElementById("result").value = 255 - getStringUTFLength(document.getElementById("licenseother").value);
}
</script>
</head>
<body>
<table width="100%">
<tr>
<td>
本输入框限制输入255个字符(汉字计算为2个字符:)
</td>
</tr>
<tr>
<td>
<textarea cols=80 rows=3 wrap="virtual" id="licenseother" onkeypress="count()" onkeyup="count()"
onblur="count();" onChange="count();"></textarea>
</td>
</tr>
<tr>
<td>
剩余字符数:<input type="text" size="3" id="result" value="255">
</td>
</tr>
</table>
</body>
</html>