views:

137

answers:

6

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.

+1  A: 

What about splitting on "\n" instead?

It will also be a problem where one line wrapped to 2 lines in the textarea.

To do it accurately like this, you could use a fixed height font and measure pixels. This could be problematic though.

alex
ouch...................!
alex
It's not that bad... I used this method in my answer.
fudgey
+1  A: 

what happened to "\n"?

Itay Moav
+1  A: 

user \n instead of \r

var text = $("#myTextArea").val();   
var lines = text.split("\n");
var count = lines.length;
console.log(count);
Marek Karbarz
+6  A: 

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
Doug Neiner
+1  A: 

The normal newline character is "\n". The convention on some systems is to also have "\r" beforehand, so on these systems "\r\n" is often found to mean a new line. In a browser, unless the user intentionally enters a "\r" by copying it from somewhere else, the newline will probably be expressed as just "\n". In either case splitting by "\n" will count the number of lines.

Danny Roberts
+2  A: 

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);
})
fudgey
you could lessen maintenance with `var lineheight = $('textarea#my-textarea').css('line-height');
alex
That doesn't seem to return the correct line height, you have to set it.
fudgey
It will only return it in pixels, I believe.
alex
Sorry, you are correct, I've modified my answer... thanks!
fudgey