js对输入框的字数限制(2009年7月4日更新)

愚人码头 撰写  

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 条评论

  1. 发表了 2009年07月4日 在 2:21 下午 | 永久链接

    额。。。 有必要么?input直接有maxlength属性吧?如果要counter,在旁边再设就是

  2. trace332
    发表了 2009年07月8日 在 2:25 下午 | 永久链接

    个人感觉的maxlength已经足够用了,不过textarea无此属性,再用JS来控制就好。

    还有一个问题就是,如果很不幸你使用的是五笔输入法,那么这段JS无效,好似五笔不触发keyup,keydown(-_-!!)

个引用通告

  1. [...] 本来也写过类似这个小功能《js对输入框的字数限制》,但是今天有朋友说要个简单的貌似twitter微博输入的功能!所以写了一个。 [...]

发表评论

Your email is never shared. 标记为 * 的为必填项目

*
*

评论时,昵称或个人网站填的是商业网站的,一概标记为垃圾评论不予显示,并设置相关网站为过滤关键字,提交到google、百度垃圾网站数据库