分享
是一种美德

JS限制textarea输入框输入字数

最近工作遇到限制textarea输入框输入字数,自己在网上搜了搜,找到一些,特此分享一下!
第一种:

<textarea onpropertychange="if(value.length>100) value=value.substr(0,100)" class="smallArea" cols="60" name="txta" rows="8"></textarea>

第二种:

<textarea onkeyup="checkLen(this)"></textarea> 
<div>您还可以输入 <span id="count">200</span> 个文字</div> 
 
<script type="text/javascript"> 
function checkLen(obj) 
{ 
    var maxChars = 200;//最多字符数 
    if (obj.value.length > maxChars) 
    obj.value = obj.value.substring(0,maxChars); 
    var curr = maxChars - obj.value.length; 
    document.getElementById_x("count").innerHTML = curr.toString(); 
} 
</script>

第三种:

<!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=gb2312" />
<meta name="robots" content="all" />
<meta name="author" content=",混蛋鱼" />
<meta name="Copyright" content="混蛋鱼VS男人猫 CopyRight 2007" />
<meta name="keywords" content="JS,Blog,ASP,designing,with,web,standards,xhtml,css,graphic,design,layout,usability,accessibility,w3c,w3,w3cn" />
<meta name="description" content="JS限制textarea输入框输入字数" />
<title>JS限制textarea输入框输入字数</title>
<SCRIPT language="javascript">
<!--
function checktext(text)
{
   allValid = true;
   for (i = 0; i < text.length; i++)
   {
    if (text.charAt(i) != " ")
    {
     allValid = false;
     break;
    }
   }
return allValid;
}
function gbcount(message,total,used,remain)
{
var max;
max = total.value;
if (message.value.length > max) {
message.value = message.value.substring(0,max);
used.value = max;
remain.value = 0;
alert("留言不能超过 200 个字!");
}
else {
used.value = message.value.length;
remain.value = max - used.value;
}
}
-->
</script>
<style type="text/css">
<!--
* {padding:0; margin:0;}
body, html {text-align:left; font-size:12px; line-height:150%; margin:0 auto; background:#fff; padding-top:20px;}
fieldset {padding:10px; width:550px; margin:0 auto;}
legend {font-size:14px; font-weight:bold;}
.inputtext {border:none; background:#fff;}
-->
</style>
</head>
<body>
<form action="SaveData.asp" method="post" onSubmit="return datacheck();">
<fieldset><legend>请输入内容</legend>
<textarea name="Memo" rows="10" wrap=PHYSICAL cols="75" onKeyDown="gbcount(this.form.Memo,this.form.total,this.form.used,this.form.remain);" onKeyUp="gbcount(this.form.Memo,this.form.total,this.form.used,this.form.remain);"></textarea>
<p>最多字数:
<input disabled maxLength="4" name="total" size="3" value="200" class="inputtext">
已用字数:
<input disabled maxLength="4" name="used" size="3" value="0" class="inputtext">
剩余字数:
<input disabled maxLength="4" name="remain" size="3" value="200" class="inputtext"></td>
</p>
</fieldset>
</form>
</body>
赞(1)
转载请注明来源地址:MN乐享 » JS限制textarea输入框输入字数

评论 抢沙发

评论前必须登录!