http://www.css88.com/archives/1591
js对输入框的字数限制,限制文本框输入的字符数,若达到数目则停止其输入!代码如下:
< !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>
<script type="text/javascript">
var textCounter=function (field,counter,maxlimit){
var charcnt = field.value.length;
if (charcnt > maxlimit) {
field.value = field.value.substring(0, maxlimit);
}else {
document.getElementById(counter).innerHTML=charcnt;
}
}
</script>
</head>
<body>
<p><span id="progressbar1">0</span>/12</p>
<form><input type="text" id="maxcharfield" size="34"/>
</form>
<script type="text/javascript">
document.getElementById("maxcharfield").onfocus = document.getElementById("maxcharfield").onkeydown = document.getElementById("maxcharfield").onkeyup = function(){
textCounter(this,'progressbar1',12);
}
</script>
</body>
</html>
—————————2009年7月4日更新——————————-
哈哈,被拍砖了,谢谢笨活儿的留言和给的方法,我照这重新做了一个:
< !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>
<p><span id="progressbar1">0</span>/12</p>
<form><input type="text" id="maxcharfield" maxlength="12"/>
</form>
<script type="text/javascript">
document.getElementById("maxcharfield").onfocus = document.getElementById("maxcharfield").onkeydown = document.getElementById("maxcharfield").onkeyup = function(){
document.getElementById("progressbar1").innerHTML = this.value.length;
}
</script>
</body>
</html>


2 条评论
额。。。 有必要么?input直接有maxlength属性吧?如果要counter,在旁边再设就是
个人感觉的maxlength已经足够用了,不过textarea无此属性,再用JS来控制就好。
还有一个问题就是,如果很不幸你使用的是五笔输入法,那么这段JS无效,好似五笔不触发keyup,keydown(-_-!!)
一 个引用通告
[...] 本来也写过类似这个小功能《js对输入框的字数限制》,但是今天有朋友说要个简单的貌似twitter微博输入的功能!所以写了一个。 [...]