<%@ Page Language="C#" AutoEventWireup="true" CodeFile="js_limit.aspx.cs" Inherits="js_limit" %>
<!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 runat="server">
<title>无标题页</title>
<script type="text/javascript">
function checkFieldLength(fieldName,fieldDesc,fieldLength)
{
var str = document.getElementById(fieldName).value;
var thelen = 0;
for(i=0;i<str.length;i++)
{
//alert(str.charCodeAt(i));
//汉字的Unicode>255
if(str.charCodeAt(i)>255)
{
thelen = thelen+2;
}else {
thelen = thelen+1;
}
}
document.getElementById("showMsg").innerText = thelen;
if(thelen>fieldLength)
{
document.getElementById("showMsg").innerText = fieldDesc;
document.getElementById(fieldName).value = CutStrLength(str,fieldLength);
}else{
return true;
}
}
function CutStrLength(str,Ilength)
{
var okLen = 0;
var len = 0;
var tmp = 0;
for(i=0;i<Ilength;i++)
{
if(str.charCodeAt(i)>255)
tmp+=2;
else
len+=1;
okLen+=1;
if(tmp+len==Ilength)
{
return (str.substring(0,okLen));
break;
}
if(tmp+len>Ilength)
{
return (str.substring(0,okLen-1)+"");
break;
}
}
}
</script>
</head>
<body>
<form id="form1" method="post" runat="server">
<textarea id="testArea" name="testArea" rows="3" cols="22" onchange="checkFieldLength('testArea', '超过允许输入的字符个数', 20);" onkeyup="checkFieldLength('testArea', '超过允许输入的字符个数', 20);">
</textarea>
<div id="testInfo">
已经输入:<span id="showMsg"></span>
</div>
</form>
</body>
</html>
|