Javascript Chrome 使用 maxlength 属性计算 textarea 中的字符错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10030921/
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
Chrome counts characters wrong in textarea with maxlength attribute
提问by Roman Pominov
Here is an example:
下面是一个例子:
$(function() {
$('#test').change(function() {
$('#length').html($('#test').val().length)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id=test maxlength=10></textarea>
length = <span id=length>0</span>
Fill textarea with lines (one character at one line) until browser allows. When you finish, leave textarea, and js code will calculate characters too.
用行(一行一个字符)填充 textarea,直到浏览器允许。完成后,离开textarea,js代码也会计算字符。
So in my case I could enter only 7 characters (including whitespaces) before chrome stopped me. Although value of maxlength attribute is 10:
所以就我而言,在 chrome 阻止我之前,我只能输入 7 个字符(包括空格)。虽然 maxlength 属性的值为 10:
采纳答案by Naftali aka Neal
Your carriage returns are considered 2 characters each when it comes to maxlength.
当涉及到 maxlength 时,您的回车每个被视为 2 个字符。
1\r\n
1\r\n
1\r\n
1
But it seems that the javascript only could one of the \r\n
(I am not sure which one) which only adds up to 7.
但似乎 javascript 只能使用其中之一\r\n
(我不确定是哪一个),加起来只有7。
回答by Tim
Here's how to get your javascript code to match the amount of characters the browser believes is in the textarea:
以下是如何让您的 javascript 代码与浏览器认为在 textarea 中的字符数量相匹配:
$(function () {
$('#test').keyup(function () {
var x = $('#test').val();
var newLines = x.match(/(\r\n|\n|\r)/g);
var addition = 0;
if (newLines != null) {
addition = newLines.length;
}
$('#length').html(x.length + addition);
})
})
Basically you just count the total line breaks in the textbox and add 1 to the character count for each one.
基本上,您只需计算文本框中的总换行符,并将每个换行符的字符数加 1。
回答by Pointy
For reasons unknown, jQuery always converts all newlines in the value of a <textarea>
to a single character. That is, if the browser gives it \r\n
for a newline, jQuery makes sure it's just \n
in the return value of .val()
.
由于未知的原因,jQuery 总是将 a 值中的所有换行符转换<textarea>
为单个字符。也就是说,如果浏览器给它\r\n
换行,jQuery 会确保它只是\n
在.val()
.
Chrome and Firefox both count the length of <textarea>
tags the same way for the purposes of "maxlength".
<textarea>
出于“maxlength”的目的,Chrome 和 Firefox 都以相同的方式计算标签的长度。
However, the HTTP spec insists that newlines be represented as \r\n
. Thus, jQuery, webkit, and Firefox all get this wrong.
但是,HTTP 规范坚持将换行符表示为\r\n
. 因此,jQuery、webkit 和 Firefox 都犯了这个错误。
The upshot is that "maxlength" on <textarea>
tags is pretty much useless if your server-side code really has a fixed maximum size for a field value.
结果是,<textarea>
如果您的服务器端代码确实有一个字段值的固定最大大小,那么标签上的“maxlength”几乎没有用。
edit— at this point (late 2014) it looks like Chrome (38) behaves correctly. Firefox (33) however still doesn't count each hard return as 2 characters.
编辑——此时(2014 年末)看起来 Chrome (38) 的行为是正确的。然而,Firefox (33) 仍然不会将每个硬返回计为 2 个字符。
回答by matt
It seems like the right method, based on Pointy's answer above, is to count all new lines as two characters. That will standardize it across browsers and match what will get sent when it's posted.
根据上面 Pointy 的回答,似乎正确的方法是将所有新行都算作两个字符。这将使其跨浏览器标准化,并匹配发布时将发送的内容。
So we could follow the spec and replace all occurrences of a Carriage Return not followed by a New Line, and all New Lines not followed by a Carriage Return, with a Carriage Return - Line Feed pair.
因此,我们可以遵循规范并使用回车符 - 换行符对替换所有出现的回车符后没有换行符,以及所有新行后没有回车符的情况。
var len = $('#test').val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
Then use that variable to display the length of the textarea value, or limit it, and so on.
然后使用该变量来显示 textarea 值的长度,或限制它,等等。
回答by anuragsn7
It looks like that javascript is considering length of new line character also.
看起来javascript也在考虑换行符的长度。
Try using:
尝试使用:
var x = $('#test').val();
x = x.replace(/(\r\n|\n|\r)/g,"");
$('#length').html(x.length);
I used it in your fiddle and it was working. Hope this helps.
我在你的小提琴中使用了它并且它正在工作。希望这可以帮助。
回答by Rene Pot
That is because an new line is actually 2 bytes, and therefore 2 long. JavaScript doesn't see it that way and therefore it will count only 1, making the total of 7 (3 new lines)
那是因为新行实际上是 2 个字节,因此长度为 2。JavaScript 不这么认为,因此它只会计算 1,总共 7(3 行新行)
回答by Stachu
Here's a more universal solution, which overrides the jQuery 'val' function. Will be making this issue into a blog post shortly and linking here.
这是一个更通用的解决方案,它覆盖了 jQuery 'val' 函数。将很快将此问题制作成博客文章并在此处链接。
var originalVal = $.fn.val;
$.fn.val = function (value) {
if (typeof value == 'undefined') {
// Getter
if ($(this).is("textarea")) {
return originalVal.call(this)
.replace(/\r\n/g, '\n') // reduce all \r\n to \n
.replace(/\r/g, '\n') // reduce all \r to \n (we shouldn't really need this line. this is for paranoia!)
.replace(/\n/g, '\r\n'); // expand all \n to \r\n
// this two-step approach allows us to not accidentally catch a perfect \r\n
// and turn it into a \r\r\n, which wouldn't help anything.
}
return originalVal.call(this);
}
else {
// Setter
return originalVal.call(this, value);
}
};
回答by Rubi saini
If you want to get remaining content length of text area then you can use match on the string containing the line breaks.
如果要获取文本区域的剩余内容长度,则可以对包含换行符的字符串使用 match。
HTML:
HTML:
<textarea id="content" rows="5" cols="15" maxlength="250"></textarea>
JS:
JS:
var getContentWidthWithNextLine = function(){
return 250 - content.length + (content.match(/\n/g)||[]).length;
}
回答by profimedica
Textareas are still not fully in sync among browsers. I noticed 2 major problems: Carriage returns and Character encodings
Textareas 在浏览器之间仍然不完全同步。我注意到两个主要问题:回车和字符编码
Carriage return
回车
By default are manipulated as 2 characters \r\n(Windows style).
默认情况下操作为 2 个字符\r\n(Windows 样式)。
The problem is that Chrome and Firefox will count it as one character. You can also select it to observe there is an invisivle character selected as a space.
问题是 Chrome 和 Firefox 会将其视为一个字符。您也可以选择它来观察是否有一个隐形字符被选为空格。
A workaround is found here:
解决方法可以在这里找到:
var length = $.trim($(this).val()).split(" ").join("").split('\n').join('').length;
Jquery word counts when user type line break
Internet explorer on the other hand will count it as 2 characters.
另一方面,Internet Explorer 会将其视为 2 个字符。
Their representation is :
他们的代表是:
Binary:00001101 00001010
Hex:0D0A
二进制:00001101 00001010
十六进制:0D0A
, and are represented in UTF-8 as 2 characters and counted for maxlength as 2 characters.
, 并在 UTF-8 中表示为 2 个字符,并将 maxlength 计为 2 个字符。
The HTML entities can be
HTML 实体可以是
1) Created from javascript code:
1) 从 javascript 代码创建:
<textarea id='txa'></textarea>
document.getElementById("txa").value = String.fromCharCode(13, 10);
2) Parsed from the content of the textarea:
2)从textarea的内容解析出来:
Ansi code:
Ansi代码:
<textarea>Line one. Line two.</textarea>
3) Inserted from keyboard Enter key
3) 从键盘输入 Enter 键
4) Defined as the multilinecontent of the textbox
4) 定义为文本框的多行内容
<textarea>Line one.
Line two.</textarea>
Character Encoding
字符编码
Character encoding of an input field like textarea is independent than the character encoding of the page. This is important if you plan to count the bytes. So, if you have a meta header to define ANSI encoding of your page (with 1 byte per character), the content of your textbox is still UTF-8 with 2 bytes per character.
像 textarea 这样的输入字段的字符编码独立于页面的字符编码。如果您计划计算字节数,这一点很重要。因此,如果您有一个元标题来定义页面的 ANSI 编码(每个字符 1 个字节),则文本框的内容仍然是 UTF-8,每个字符 2 个字节。
A workaround for the character encoding is provided here:
此处提供了字符编码的解决方法:
function htmlEncode(value){
// Create a in-memory div, set its inner text (which jQuery automatically encodes)
// Then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
function htmlDecode(value){
return $('<div/>').html(value).text();
}
回答by Fabio
var value = $('#textarea').val();
var numberOfLineBreaks = (value.match(/\n/g)||[]).length;
$('#textarea').attr("maxlength",500+numberOfLineBreaks);
works perfectly on google already in IE have to avoid the script! In IE the 'break-line' is counted only once, so avoid this solution in IE!
已经在 IE 中的 google 上完美运行必须避免脚本!在 IE 中,'break-line' 只计算一次,所以在 IE 中避免使用此解决方案!