Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding number of lines in an html textarea

Tags:

I'm writing a mobile web application where scrollbars are not displayed on the device's browser. Due to this, I'm trying to dynamically modify the height of the textarea to make it bigger, however I don't know of any way to actually get the line count on an html textarea. Any help would be greatly appreciated!

EDIT

So I realize now that it's not newlines per se, but actual line wrapping. So when one line finishes it wraps the text to the next line. It appears as if it is a new line. Any way to count the number of these? Thanks!

like image 350
Kyle Avatar asked Sep 12 '10 23:09

Kyle


People also ask

How do I count the number of lines in a textarea?

split("\r"); var count = lines. length; console. log(count); It always gives '1' no matter how many lines.

How do I count the number of lines in HTML?

Divide the Element's Height by its Line Height To get the number of lines in an element, we can divide the element's height by its line-height.

How do I count text lines inside a DOM element?

To count number of text lines inside DOM element, we will use the following approach. Obtain the total height of content inside the DOM element. Obtain the height of one line. By dividing the total height of the content by the height of one line, you get the total number of lines inside the element.

What is rows in textarea?

The HTML textarea rows Attribute is used to specify the number of visible text lines for the control i.e the number of rows to display. It also specifies the visible height of the Textarea.


2 Answers

The number of lines in the textarea would be

textarea.value.match(/\n/g).length + 1 
like image 134
Delan Azabani Avatar answered Oct 10 '22 06:10

Delan Azabani


I have created a plugin to handle line counting and wrap detection in a <textarea>.
I hope someone can use it.

Code on BitBucket

Sample Usage

var result = $.countLines("#textarea");  result.actual   // The number of lines in the textarea. result.wraps    // The number of lines in the textarea that wrap at least once. result.wrapped  // The total number of times all lines wrap. result.blank    // The number of blank lines. result.visual   // The approximate number of lines that the user actually sees in the textarea   

Working Demonstration

/*! Textarea Line Count - v1.4.1 - 2012-12-06   * https://bitbucket.org/MostThingsWeb/textarea-line-count   * Copyright (c) 2012 MostThingsWeb (Chris Laplante); Licensed MIT */    (function($) {    $.countLines = function(ta, options) {      var defaults = {        recalculateCharWidth: true,        charsMode: "random",        fontAttrs: ["font-family", "font-size", "text-decoration", "font-style", "font-weight"]      };        options = $.extend({}, defaults, options);        var masterCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";      var counter;        if (!ta.jquery) {        ta = $(ta);      }        var value = ta.val();      switch (options.charsMode) {        case "random":          // Build a random collection of characters          options.chars = "";          masterCharacters += ".,?!-+;:'\"";          for (counter = 1; counter <= 12; counter++) {            options.chars += masterCharacters[(Math.floor(Math.random() * masterCharacters.length))];          }          break;        case "alpha":          options.chars = masterCharacters;          break;        case "alpha_extended":          options.chars = masterCharacters + ".,?!-+;:'\"";          break;        case "from_ta":          // Build a random collection of characters from the textarea          if (value.length < 15) {            options.chars = masterCharacters;          } else {            for (counter = 1; counter <= 15; counter++) {              options.chars += value[(Math.floor(Math.random() * value.length))];            }          }          break;        case "custom":          // Already defined in options.chars          break;      }        // Decode chars      if (!$.isArray(options.chars)) {        options.chars = options.chars.split("");      }        // Generate a span after the textarea with a random ID      var id = "";      for (counter = 1; counter <= 10; counter++) {        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(options.fontAttrs, function(i, v) {        span.css(v, ta.css(v));      });        // Get the number of lines      var lines = value.split("\n");      var linesLen = lines.length;        var averageWidth;        // Check if the textarea has a cached version of the average character width      if (options.recalculateCharWidth || ta.data("average_char") == null) {        // 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 = options.chars;          var charLen = chars.length;        var totalWidth = 0;          $.each(chars, function(i, v) {          span.text(v);          totalWidth += span.width();        });          // Store average width on textarea        ta.data("average_char", Math.ceil(totalWidth / charLen));      }        averageWidth = ta.data("average_char");        // We are done with the span, so kill it      span.remove();        // 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;      var wrappingCount = 0;      var blankLines = 0;        $.each(lines, function(i, v) {        // Calculate width of line        lineWidth = ((v.length + 1) * averageWidth) + missingWidth;        // Check if the line is wrapped        if (lineWidth >= ta.outerWidth()) {          // Calculate number of times the line wraps          var wrapCount = Math.floor(lineWidth / ta.outerWidth());          wrappingCount += wrapCount;          wrappingLines++;        }          if ($.trim(v) === "") {          blankLines++;        }      });        var ret = {};      ret["actual"] = linesLen;      ret["wrapped"] = wrappingLines;      ret["wraps"] = wrappingCount;      ret["visual"] = linesLen + wrappingCount;      ret["blank"] = blankLines;        return ret;    };  }(jQuery));        result = jQuery.countLines("#textarea");    jQuery('#display').html(    '<span>Actual: ' + result.actual + '</span>' +    '<span>Blank: ' + result.blank + '</span>' +    '<span>Visual: ' + result.visual + '</span>' +    '<span>Wrapped: ' + result.wrapped + '</span>' +    '<span>Wraps: ' + result.wraps + '</span>'  );
#textarea {    width: 150px;    height: 80px;  }  #display span {    display: block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <textarea id="textarea">text  here      this is a longer line so that it will wrap in the box longer longer longer</textarea>    <div id="display"></div>
like image 39
Chris Laplante Avatar answered Oct 10 '22 06:10

Chris Laplante