Problems with textarea character counter

0

I want to improve this function, because when you break the line, it does not count the characters properly:

$(function(){

    $("#maxlength").keyup(function(event){

        var target = $("#content-countdown");
        var max = target.attr('title');
        var len = parseInt($(this).val().length);
        var remain = max - len;

        if (len > max) {
            var val = $(this).val();
            $(this).val(val.substr(0, max));

            remain = 0;
        }

        target.html(remain);

    });

});

HTML

<textarea name="body" maxlength="100" id="maxlength" placeholder="O que está acontecendo?"></textarea>
<input type="submit" name="send" value="Post">
<span id="content-countdown" title="100">100</span>
    
asked by anonymous 29.10.2015 / 00:50

1 answer

1

Using the Fiddle created by Gabriel Rodrigues; I made some changes, removing the maxlength of the textarea (which caused the limitation of the lines, I do not know the reason) and changed the keydown event to input; which will also be fired when text is pasted into Textarea.

You can check the result below:

link

EDIT: Apparently it's a Webkit bug. Since in windows a line break is equivalent to \ r \ n (carriage return and line feed) characters, I believe that when counting the number of characters the line breaks count as two characters instead of one. In Opera the same problem happens.

    
29.10.2015 / 12:16