Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of lines in a textarea?

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.

like image 579
Ali Avatar asked Jan 10 '10 02:01

Ali


People also ask

How to count number of lines in textarea?

val(); var lines = text. split("\r"); var count = lines. length; console. log(count);


2 Answers

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

like image 91
Mottie Avatar answered Sep 29 '22 03:09

Mottie


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 
like image 40
Doug Neiner Avatar answered Sep 29 '22 02:09

Doug Neiner