Javascript 文本区字符限制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5533053/
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
textarea character limit
提问by Web_Designer
I would like to be able to limit the number of characters in a textarea. The method I am using works great in Google Chrome, but is slow in Firefox, and doesn't work in IE.
我希望能够限制 textarea 中的字符数。我使用的方法在 Google Chrome 中效果很好,但在 Firefox 中很慢,在 IE 中不起作用。
Javascript:
Javascript:
function len(){
t_v=textarea.value;
if(t_v.length>180){
long_post_container.innerHTML=long_post;
post_button.className=post_button.className.replace('post_it_regular','post_it_disabled');
post_button.disabled=true;
}
else{
long_post_container.innerHTML="";
post_button.className=post_button.className.replace('post_it_disabled','post_it_regular');
post_button.disabled=false;
}
if(t_v.length>186){
t_v=t_v.substring(0,186);
}
}
HTML:
HTML:
<textarea id="user_post_textarea" name="user_post_textarea" cols="28" rows="1" onkeypress="len();" onkeyup="len();"></textarea>
Javascript at bottom of body element:
body 元素底部的 Javascript:
textarea=document.getElementById('user_post_textarea');
回答by Web_Designer
I found a good solution that uses the maxlengthattribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.
我找到了一个很好的解决方案,它在浏览器支持的情况下使用maxlength属性,并在不支持的浏览器中回退到不显眼的 javascript pollyfill。
Thanks to @Dan Tello's commentI fixed it up so it works in IE7+ as well:
感谢@Dan Tello 的评论,我修复了它,因此它也适用于 IE7+:
HTML:
HTML:
<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>
Javascript:
Javascript:
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("text"));
There is no such thingas a minlength
attribute in HTML5.
For the following input types: number
, range
, date
, datetime
, datetime-local
, month
, time
, and week
(which aren't fully supported yet) use the min
and max
attributes.
有没有这样的事情作为一个minlength
在HTML5属性。
对于以下输入类型:number
、range
、date
、datetime
、datetime-local
、month
、time
和week
(尚未完全支持)使用min
和max
属性。
回答by James South
This is entirely untested but it should do what you need.
这完全未经测试,但它应该可以满足您的需求。
Update : here's a jsfiddle to look at. Seems to be working. link
更新:这里有一个 jsfiddle 可以查看。似乎正在工作。关联
You would past it into a js file and reference it after your jquery reference. You would then call it like this..
您可以将它粘贴到一个 js 文件中,并在您的 jquery 引用之后引用它。然后你会这样称呼它..
$("textarea").characterCounter(200);
A brief explanation of what is going on..
对正在发生的事情的简要说明..
On every keyup event the function is checking what type of key is pressed. If it is acceptable the the counter will check the count, trim any excess and prevent any further input once the limit is reached.
在每个 keyup 事件中,该函数都会检查按下了哪种类型的键。如果可以接受,计数器将检查计数,修剪任何多余的内容并在达到限制后阻止任何进一步的输入。
The plugin should handle pasting into the target too.
该插件也应该处理粘贴到目标中。
; (function ($) {
$.fn.characterCounter = function (limit) {
return this.filter("textarea, input:text").each(function () {
var $this = $(this),
checkCharacters = function (event) {
if ($this.val().length > limit) {
// Trim the string as paste would allow you to make it
// more than the limit.
$this.val($this.val().substring(0, limit))
// Cancel the original event
event.preventDefault();
event.stopPropagation();
}
};
$this.keyup(function (event) {
// Keys "enumeration"
var keys = {
BACKSPACE: 8,
TAB: 9,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
};
// which normalizes keycode and charcode.
switch (event.which) {
case keys.UP:
case keys.DOWN:
case keys.LEFT:
case keys.RIGHT:
case keys.TAB:
break;
default:
checkCharacters(event);
break;
}
});
// Handle cut/paste.
$this.bind("paste cut", function (event) {
// Delay so that paste value is captured.
setTimeout(function () { checkCharacters(event); event = null; }, 150);
});
});
};
} (jQuery));
回答by Daniel Montenegro
I think that doing this might be easier than most people think!
我认为这样做可能比大多数人想象的要容易!
Try this:
尝试这个:
var yourTextArea = document.getElementById("usertext").value;
// In case you want to limit the number of characters in no less than, say, 10
// or no more than 400.
if (yourTextArea.length < 10 || yourTextArea.length > 400) {
alert("The field must have no less than 10 and no more than 400 characters.");
return false;
}
Please let me know it this was useful. And if so, vote up! Thx!
请让我知道这很有用。如果是这样,请投票!谢谢!
Daniel
丹尼尔
回答by Rohit Gupta
using maxlength attribute of textarea would do the trick ... simple html code .. not JS or JQuery or Server Side Check Required....
使用 textarea 的 maxlength 属性可以解决问题......简单的 html 代码......不是 JS 或 JQuery 或需要服务器端检查......
回答by kennebec
This works on keyup and paste, it colors the text red when you are almost up to the limit, truncates it when you go over and alerts you to edit your text, which you can do.
这适用于键盘和粘贴,当您几乎达到限制时,它会将文本着色为红色,当您过去时将其截断并提醒您编辑文本,您可以这样做。
var t2= /* textarea reference*/
var t2= /* 文本区域引用*/
t2.onkeyup= t2.onpaste= function(e){
e= e || window.event;
var who= e.target || e.srcElement;
if(who){
var val= who.value, L= val.length;
if(L> 175){
who.style.color= 'red';
}
else who.style.color= ''
if(L> 180){
who.value= who.value.substring(0, 175);
alert('Your message is too long, please shorten it to 180 characters or less');
who.style.color= '';
}
}
}
回答by Nick B
Quick and dirty universal jQuery version. Supports copy/paste.
快速而肮脏的通用 jQuery 版本。支持复制/粘贴。
$('textarea[maxlength]').on('keypress mouseup', function(){
return !($(this).val().length >= $(this).attr('maxlength'));
});
回答by El Colo
I believe if you use delegates, it would work..
我相信如果您使用委托,它会起作用..
$("textarea").on('change paste keyup', function () {
var currText = $(this).val();
if (currText.length > 500) {
var text = $(this).text();
$(this).text(text.substr(0, 500));
alert("You have reached the maximum length for this field");
}
});
回答by Dejan Marjanovic
Try using jQuery to avoid cross browser compatibility problems...
尝试使用 jQuery 来避免跨浏览器兼容性问题...
$("textarea").keyup(function(){
if($(this).text().length > 500){
var text = $(this).text();
$(this).text(text.substr(0, 500));
}
});
回答by Christian
... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...
It ought to work.
它应该工作。
回答by Jakob Alexander Eichler
I have written my method for this, have fun testing it on your browsers, and give me feedback.
我为此编写了我的方法,在您的浏览器上测试它很有趣,并给我反馈。
cheers.
干杯。
function TextareaControl(textarea,charlimit,charCounter){
if(
textarea.tagName.toLowerCase() === "textarea" &&
typeof(charlimit)==="number" &&
typeof(charCounter) === "object" &&
charCounter.innerHTML !== null
){
var oldValue = textarea.value;
textarea.addEventListener("keyup",function(){
var charsLeft = charlimit-parseInt(textarea.value.length,10);
if(charsLeft<0){
textarea.value = oldValue;
charsLeft = charlimit-parseInt(textarea.value.length,10);
}else{
oldValue = textarea.value;
}
charCounter.innerHTML = charsLeft;
},false);
}
}