javascript 限制文本区域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7645209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limit the textarea
提问by Mike Vierwind
Possible Duplicate:
limit number of characters entered in textarea
可能的重复:
限制在 textarea 中输入的字符数
How can I set a limit on the number of characters possible to go into a textarea? I have a textarea that you can put max 50 characters into it. How can i make this with Javascript. I want that the enters are also characters so people wont put lots of enters
.
如何设置可以进入 textarea 的字符数限制?我有一个 textarea,您最多可以在其中放入 50 个字符。我怎样才能用 Javascript 做到这一点。我希望输入也是字符,所以人们不会放很多enters
.
采纳答案by JellyBelly
try this:
试试这个:
<script language="javascript" type="text/javascript">
function imposeMaxLength(Object, MaxLen)
{
return (Object.value.length <= MaxLen);
}
</script>
<textarea name="myName" onkeypress="return imposeMaxLength(this, 15);" ><textarea>
or
或者
<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
<form name="myform">
<textarea name="limitedtextarea" onKeyDown="limitText(this.form.limitedtextarea,this.form.countdown,100);"
onKeyUp="limitText(this.form.limitedtextarea,this.form.countdown,100);">
</textarea><br>
<font size="1">(Maximum characters: 100)<br>
You have <input readonly type="text" name="countdown" size="3" value="100"> characters left.</font>
</form>
回答by Mike Vierwind
the above code with onkeypress will not work with copy/paste or drag & drop you can use the "oninput" event but it is not supported in all mayor browsers (ie8+) the best way to limit/filter a form field is this:
上面带有 onkeypress 的代码不适用于复制/粘贴或拖放,您可以使用“oninput”事件,但并非所有市长浏览器(ie8+)都支持它限制/过滤表单字段的最佳方法是:
<form id="a" method="post" action="?hey">
<textarea id="t" data-maxlen="10"></textarea>
<input type="submit" value="submit me">
</form>
<script>
var aa = document.getElementById("a");
var tt = document.getElementById("t");
aa.onsubmit=function()
{
if(tt.value.length > parseInt(tt.getAttribute("data-maxlen")))
{
tt.style.backgroundColor="red";
return false;
}
else
{
tt.style.backgroundColor="white";
return true;
}
};
</script>
but in any case you will need a server-side check
但无论如何,您都需要进行服务器端检查
HTH!
哼!