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

I have a textarea with the attribute maxlength set to 350 & it works fine, it also counts enterlin

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742370900a4431238.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信