Redwall Redwall - 4 years ago 199
Javascript Question

Limit number of lines (rows + Enter key press) in Text area plus show Line Count

I am looking to find a way using jquery / html / or even css to do the following.

My text area is fixed size, 1 font size/type, and I want to be able to do the following.


  • Limit number of lines to 18 lines

  • Display the number of lines the user has used so far (Kind of like twitter approach with characters but displaying lines used)



Line Definition: A line for my project is either when the user presses enter on the keyboard and goes to a new line, OR when a new row / line is created in the textarea by naturally typing continuously int he textarea. I basically have a fixed size textarea and the user cannot go outside these limits I set.

Answer Source

I will not provide any code snippets for your problem but just an approach of how i'm seeing the solution. Basing your algorithm on the font.js javascript library, you could retrieve the length in pixels of the text and of all the caracters in the text. If you're using a unique font in your textbox you could know when a line is completed each time the number of pixels in a line equals or is inferior to the actual number of pixels used in a new line. In pseudo-code it would look like this :

var textBoxLineInPixels = 300 //or getting the actual number through DOM;

onChangeEvent    {
   var totalNumberOfPixels = getNumberOfPixelsFromElement(idToYourTextBox);
   var numberOfLinesUsed = totalNumberOfPixels / textBoxLineInPixels;
   update(idToYourNumberOfLinesContainer, numberOfLinesUsed);
}

Dividing the total number of pixels in your textarea by the the number of pixels in a line will give you the current number of lines used in your textarea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download