<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>统计文本区域字节数,超出部分无效</title>
<script language="javascript">
//统计文本区域字节数函数
function textareastrlen(str){
var len;
var i;
len = 0;
for (i=0;i<str.length;i++){
if (str.charCodeAt(i)>255){
len+=2;
}
else{
len++;
}
}
return len;
}
function countChar(textareaName,spanName)//显示文本区域字数函数
{
document.getElementById(spanName).innerHTML="共" + document.getElementById(textareaName).value.length +"个字;" + textareastrlen(document.getElementById(textareaName).value) + "个字节。";
}
function substr(str,len){
if(!str||!len||len<=0||textareastrlen(str)<len){
return '';
}
//预期计数:中文2字节,英文1字节
var a=0;
//循环计数
var i=0;
//临时字串
var temp='';
for (i=0; i<str.length; i++ ){
if (str.charCodeAt(i)>255){
//按照预期计数增加2
a+=2;
}
else{
a++ ;
}
//如果增加计数后长度大于限定长度,就直接返回临时字符串
if(a>len){
return temp;
}
//将当前内容加到临时字符串
temp+=str.charAt(i);
}
//如果全部是单字节字符,就直接返回源字符串
return str;
}
<!--Begin
function checkMaxInput(textareaName,spanName,maxLen){
if(textareastrlen(document.getElementById(textareaName).value)>maxLen){//if too long.... trim it!
document.getElementById(textareaName).value=substr(document.getElementById(textareaName).value,maxLen);
yuxiLen=maxLen-textareastrlen(document.getElementById(textareaName).value);
document.getElementById(spanName).innerHTML="总共可输入" + maxLen +"个字节;还可以输入" + yuxiLen + "个字节。";
}
else{//otherwise, update 'characters left' counter
yuxiLen=maxLen-textareastrlen(document.getElementById(textareaName).value);
document.getElementById(spanName).innerHTML="总共可输入" + maxLen +"个字节;还可以输入" + yuxiLen + "个字节。";
}
}
//End -->
</script>
</head>
<body>
<table width="100%" height="100" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td width="15%" align="right" bgcolor="#FFFFFF"><strong>信息标题一:</strong></td>
<td width="85%" bgcolor="#FFFFFF"><input name="Title1" type="text" id="Title1" onkeydown="countChar('Title1','num1');" onkeyup="countChar('Title1','num1');" value="" size="60" />
<span id="num1"></span></td>
</tr>
<tr>
<td width="15%" align="right" bgcolor="#FFFFFF"><strong>信息标题二:</strong></td>
<td width="85%" bgcolor="#FFFFFF"><input name="Title2" type="text" id="Title2" value="" size="60" onkeydown="checkMaxInput('Title2','num2',20)" onkeyup="checkMaxInput('Title2','num2',20)" />
<span id="num2"></span></td>
</tr>
</table>
</body>
</html>