textarea文本框输入字数判断js

javascript

2009-08-18 10:09

<!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=utf-8" />
<title>字数统计</title>
</head>

<body><textarea name="" cols="" rows="" id="t" onkeyup="countt(this.id,300);"></textarea>
<span id="num">0</span>


<script language="javascript">

function countt(str,n){
var num=document.getElementById("num");  
var tt=document.getElementById(str);
if (DataLength(tt.value)>n*2){
tt.value=SetString(tt.value,n*2);
}
num.innerHTML=Math.floor(DataLength(tt.value)/2);

}


function DataLength(fData)
{var intLength=0;
for (var i=0;i<fData.length;i++)
{
   if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255))
    intLength=intLength+2;
   else
    intLength=intLength+1;
}
return intLength;
}

function SetString(str,len){
var strlen = 0;
var s = "";
for(var i = 0;i < str.length;i++){
if(str.charCodeAt(i) > 128){
strlen += 2;
}else{
strlen++;
}
s += str.charAt(i);
if(strlen >= len){
return s ;
}
}
return s;
}

</script>

</body>
</html>