最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Textarea | val().length not counting "EnterLine Breaks" in chrome - Stack Overflow

programmeradmin1浏览0评论

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: /

Note this bug only occurs 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.

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/udp9oxx4/

Note this bug only occurs in chrome.

Share Improve this question edited Mar 15, 2016 at 8:09 Oscar LT 7971 gold badge4 silver badges24 bronze badges asked Mar 15, 2016 at 6:41 Imran BughioImran Bughio 4,9412 gold badges31 silver badges54 bronze badges 2
  • yes it is showing the msg over 350 charecters in chrome – Brave Soul Commented Mar 15, 2016 at 6:45
  • 1 I was just burned by this one. As you said, the value of textarea doesn't include CR/LFs. I had some code that passed the client validation but it failed on the server because the value had more characters than allowed. – boggy Commented Jun 13, 2017 at 18:25
Add a ment  | 

1 Answer 1

Reset to default 6
$("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/3wpqd4nr/

Fiddle

发布评论

评论列表(0)

  1. 暂无评论