Untested, but try this:
var linecount = document.getElementById("myTextarea").value.split("\n").length;
Edit
To detect lines that wrap into the next line, this is the general process:
- Calculate the average width of a character, as displayed by the textarea
- For each line, estimate the width of the line
- If this width is greater than the width of the
Here is the code I came up with (I will be turning this into a full-fledged jQuery plugin, by the way):
(function($){
$.countLines = function(textarea){
// The textarea
var ta;
if (typeof textarea == "string")
ta = $(textarea);
else if (typeof textarea == "object")
ta = textarea;
// Generate a span after the textarea with a random ID
var id = "";
for ( var i = 1; i <= 10; i++)
id += (Math.floor(Math.random() * 10) + 1);
ta.after("<span id='s" + id + "'></span>");
var span = $("#s" + id);
// Hide the span
span.hide();
// Apply the font properties of the textarea to the span class
$.each(["font-family", "font-size", "text-decoration", "font-style", "font-weight"], function(i, v){
span.css(v, ta.css(v));
});
// Get the textarea value
var value = ta.val();
// Get the number of lines
var lines = value.split("\n");
var linesLen = lines.length;
// Get a pretty good estimation of the width of a character in the textarea. To get a better average, add more characters and symbols to this list
var chars = ["D", "E", "C", "I", "D", "Q", "?", "!", ".", ","];
var charLen = chars.length;
var totalWidth = 0;
$.each(chars, function(i, v){
span.text(v);
totalWidth += span.width();
});
// Calculate average width of character
var averageWidth = Math.ceil(totalWidth / charLen);
// Determine missing width (from padding, margins, borders, etc); this is what we will add to each line width
var missingWidth = (ta.outerWidth() - ta.width()) * 2;
// Calculate the number of lines that occupy more than one line
var lineWidth;
var wrappingLines = 0;
$.each(lines, function(i, v){
// Calculate width of line
lineWidth = (v.length * averageWidth) + missingWidth;
// Check if the line is wrapped
if (lineWidth > ta.outerWidth())
wrappingLines++;
});
var ret = {};
ret["actual"] = linesLen;
ret["wrapped"] = wrappingLines;
ret["visual"] = linesLen + wrappingLines;
return ret;
};
})(jQuery);
To use it:
alert($.countLines($("#ta")).wrapped);
... will give the number of times a line wraps (but only once per line, in my plugin I will fix this shortcoming).
Also, alert($.countLines($("#ta")).actual);
gives total lines, whether they wrap or not and
alert($.countLines($("#ta")).visual);
will give the total lines plus wrapped lines. Hope you find this useful, and be sure to check back in the next day or two as I will post a link to the plugin when I finish it.