Problems with textarea character counter

Asked

Viewed 320 times

0

I want to improve this function, because when you break the line, it doesn’t 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>
  • When he breaks the line he doesn’t count or count ? why when he breaks the line he is giving spaces these spaces are counted as characters

  • when I break the line to the maximum it only counts 50 characters, but can’t type anymore.

  • I did a test here and I didn’t find this problem... http://jsfiddle.net/filadown/tv0rrv0r/

  • In the secure textarea enter until it stops, appears 50, I want it to stay 0.

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 don’t know the reason) and changed the event from keydown to input; which will also be triggered when text is pasted inside the Textarea.

You can check the result below:

http://jsfiddle.net/tv0rrv0r/1/

EDIT: Apparently it’s a Webkit bug. Considering that in windows a line break is equivalent to the characters r n (Carriage Return and line feed), I believe that when counting the number of characters the line breaks are counted as two characters and not one. In Opera the same problem happens.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.