昨天应朋友要求,做了一个简单的限制文本长度的示例,以对应数据库中一个中文字符占2个字节的问题。
源码如下:
<script>
functiongetStringUTFLength(str){
varvalue=str.replace(/[^\x00-\xff]/g,"");
returnvalue.length;
}
functionleftUTFString(str,len){
if(getStringUTFLength(str)<=len)
returnstr;
varvalue=str.substring(0,len);
while(getStringUTFLength(value)>len){
value=value.substring(0,value.length-1);
}
returnvalue;
}
functioncount(){
varvalue=document.getElementById("licenseother").value;
value=value.replace(/[\u4e00-\u9fa5]/g,"");
//alert(value.length);
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>
<tablewidth="100%">
<tr><td>
本输入框限制输入255个字符(汉字计算为2个字符:)
</td></tr>
<tr><td>
<textareacols=80rows=3wrap="virtual"id="licenseother"onkeypress="count()"onkeyup="count()"onblur="count();"onChange="count();"></textarea>
</td></tr>
<tr><td>
剩余字符数:<inputtype="text"size="3"id="result"value="255">
</td></tr>
</table>
}
来自:http://liu2liu2.spaces.live.com/blog/cns!54B12917375EF5A0!267.entry
本文提供了一个简单的JavaScript示例代码,用于限制文本框内的字符数量,并考虑到中文字符占用两个字节的特点。通过实时更新剩余字符数,帮助用户控制输入长度。
1541

被折叠的 条评论
为什么被折叠?



