Count textarea characters

前端 未结 11 2049
走了就别回头了
走了就别回头了 2020-11-28 07:29

I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, wh

11条回答
  •  北海茫月
    2020-11-28 07:52

    I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.

    $(function() {
      $("#myTextArea").on("input propertychange", function(event) {
        var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
    
        $("#counter").html(curlen);
      });
    });
    
    $("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
    
    
    Size:

提交回复
热议问题