InvoiceBerry Blog

Small Business | Invoicing | Marketing | Entrepreneurship | Freelancing

Dynamically change the height of a textarea based on the text (Javascript)

Written by on March 21, 2011

As mentioned in this post, we will publish some solutions and code snippets of problems we’ve encountered and solved.

The Problem

On our invoices, quotes, expenses and items pages we need to have descriptions. Rather then having a text box with 5 or 10 rows as standard we decided that we want to only show one row as standard and then dynamically add more rows whenever needed.

Try our online invoicing software for free

Send professional-looking invoices
Accept online payments with ease
Keep track of who's paid you

Start sending invoices

Our Solution

This means we are only going to change the number of rows (height) whenever someone either hits the ENTER button (line break) or when the text is a certain length and an automatic line break should occur.

We first need the HTML:

<textarea id="description_id" onkeyup="new do_resize(this);" cols="20" rows="1" name="description_name"></textarea>

 

This just creates a textarea with one row. We also tell it to execute the JavaScript function “do_resize” every time we hit a key (onkeyup).

Then we need the JavaScript:

function do_resize(textbox) {

 var maxrows=5; 
  var txt=textbox.value;
  var cols=textbox.cols;

 var arraytxt=txt.split('\n');
  var rows=arraytxt.length; 

 for (i=0;i<arraytxt.length;i++) 
  rows+=parseInt(arraytxt[i].length/cols);

 if (rows>maxrows) textbox.rows=maxrows;
  else textbox.rows=rows;
 }

 

The JavaScript function takes the value of the textarea and splits it into arrays whenever a line break (“\n”) occurs. The length of the array then gives us the amount of rows we need.

However, we also have to check the length of every string in the array, as we need to add a new row for strings which are longer than 20 characters (remember we set our cols variable to 20).

We hope this little code helps some people out there.
Please do not hesitate to leave a comment for feedback, asking for clarification or errors.

Small Business Finance 101

Download our free guide to learn the fundamentals of finance that will help make your small business more efficient and successful.

Ready to start invoicing your clients with InvoiceBerry?

Sign up to our free trial account. No credit card required.

Sign Up Now
We use cookies to give you a better experience. Check out our privacy policy for more information.
OK