I found that the accepted answer didn't exactly work with textarea
s 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() {_x000D_
$("#myTextArea").on("input propertychange", function(event) {_x000D_
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;_x000D_
_x000D_
$("#counter").html(curlen);_x000D_
});_x000D_
});_x000D_
_x000D_
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<textarea id="myTextArea"></textarea><br>_x000D_
Size: <span id="counter" />
_x000D_