Tuesday, September 1, 2009

Auto Resize TextAreas in Javascript

This function will automatically resize your text areas as the user types. Here is a struts example:

You will call the function with this code.

<html:textarea rows="2" name="start" property="principles" onkeyup="javascript:resizeTextArea(this)"/>

Here is the function that will resize your textboxes.


function resizeTextArea(txtBox)
{
nCols = txtBox.cols;
sVal = txtBox.value;
nVal = sVal.length;
nRowCnt = 1;
for (i=0;i<nVal;i++ )
{ if (sVal.charAt(i).charCodeAt(0) == 13) { nRowCnt +=1; } }
if (nRowCnt < (nVal / nCols)) { nRowCnt = 1 +(nVal / nCols); }
txtBox.rows = nRowCnt+1;
}

1 comments:

Iulian and Rachel September 2, 2009 9:48 AM  

This works cool, but if you type a series of carriage returns to add spaces between paragraphs, it looses sync and doesn't properly account for the spaced lines... Not sure why, the code seems to check for each #13...