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

柔情痞子 提交于 2020-05-29 05:06:21

问题


I have a textarea with the attribute maxlength set to 350 & it works fine, it also counts enter/line break as a character.

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:

$("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.

Here is a fiddle to play with: https://jsfiddle.net/udp9oxx4/

Note this bug only occurs in chrome.


回答1:


$("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. Just add this code in front of the function and it will work just fine.

https://jsfiddle.net/3wpqd4nr/

Fiddle



来源:https://stackoverflow.com/questions/36004311/textarea-val-length-not-counting-enter-line-breaks-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!