What I would like is to count the number of lines in a textarea, e.g:
line 1 line 2 line 3 line 4
should count up to 4 lines. Basically pressing enter once would transfer you to the next line
The following code isn't working:
var text = $("#myTextArea").val(); var lines = text.split("\r"); var count = lines.length; console.log(count);
It always gives '1' no matter how many lines.
val(); var lines = text. split("\r"); var count = lines. length; console. log(count);
The problem with using "\n" or "\r" is it only counts the number of returns, if you have a line that is long it could wrap and then it wouldn't be counted as a new line. This is an alternative way to get the number of lines - so it may not be the best way.
Edit (thanks alex):
Script
$(document).ready(function(){ var lht = parseInt($('textarea').css('lineHeight'),10); var lines = $('textarea').attr('scrollHeight') / lht; console.log(lines); })
Update: There is a much more thorough answer here: https://stackoverflow.com/a/1761203/145346
If you are just wanting to test hard line returns, this will work cross platform:
var text = $("#myTextArea").val(); var lines = text.split(/\r|\r\n|\n/); var count = lines.length; console.log(count); // Outputs 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With