Javascript – Chrome counts characters wrong in textarea with maxlength attribute


Here is an example:

$(function() {
  $('#test').change(function() {
<script src=""></script>
<textarea id=test maxlength=10></textarea>
length = <span id=length>0</span>

Fill textarea with lines (one character at one line) until browser allows.
When you finish, leave textarea, and js code will calculate characters too.

So in my case I could enter only 7 characters (including whitespaces) before chrome stopped me. Although value of maxlength attribute is 10:


Best Solution

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

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