Chrome counts characters wrong in textarea with maxlength attribute Chrome counts characters wrong in textarea with maxlength attribute google-chrome google-chrome

Chrome counts characters wrong in textarea with maxlength attribute


Here's how to get your javascript code to match the amount of characters the browser believes is in the textarea:

http://jsfiddle.net/FjXgA/53/

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


Your carriage returns are considered 2 characters each when it comes to maxlength.

1\r\n1\r\n1\r\n1

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.


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.

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.