简体   繁体   English

Textarea | val()。长度不计算chrome中的“Enter / Line Breaks”

[英]Textarea | val().length not counting “Enter/Line Breaks” in chrome

I have a textarea with the attribute maxlength set to 350 & it works fine, it also counts enter/line break as a character. 我有一个textarea属性maxlength设置为350 &它工作正常,它还将输入/换行计为一个字符。

I also have to show a error message if user try to type more than or reaches to 350 character limit for which I am using this code: 如果用户尝试键入超过或达到350字符限制,我还必须显示错误消息,我使用此代码:

$("textarea").keyup(function (e) {
    if($(this).val().length >=350){
        $('.error').show();
    }else{
        $('.error').hide();
    }
});

It works but in chrome it doesn't count enter/line break but maxlength does as a result if a user is breaking text in multiple lines, he do stops typing after 350 character but don't see any message. 它可以工作,但在chrome中它不计入输入/换行,但是如果用户在多行中断文本,则maxlength会这样做,他确实在350个字符后停止输入但没有看到任何消息。

Here is a fiddle to play with: https://jsfiddle.net/udp9oxx4/ 这是一个小提琴: https//jsfiddle.net/udp9oxx4/

Note this bug only occurs in chrome. 请注意,此错误仅发生在chrome中。

$("textarea").keyup(function (e) {

var isChrome = window.chrome;
if(isChrome){
var value = $(this).val().replace(/(\r\n|\n|\r)/g,"  ");
}
else{
var value = $(this).val();
}

        if(value.length >=350){
            $('.error').show();
        }else{
            $('.error').hide();
        }
    });

Chrome counts line break as 2 character, so it counts the characters wrong. Chrome会将换行计为2个字符,因此会将字符计为错误。 Just add this code in front of the function and it will work just fine. 只需在函数前添加此代码,它就可以正常工作。

https://jsfiddle.net/3wpqd4nr/ https://jsfiddle.net/3wpqd4nr/

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM