JavaScript Autosize TextArea - .charCodeAt

Printer Friendly Version


Here's a little diddy that could make your code articles a lot easier to write and still look good straight out of your IDE. The function ResizeTextArea will look at the contents of your <TEXTAREA> tag and autosize the rows based on how much content is contained.

Here's a little diddy that could make your code articles a lot easier to write and still look good straight out of your IDE. The function ResizeTextArea will look at the contents of your <TEXTAREA> tag and autosize the rows based on how much content is contained. You could then simply run a resize in the <BODY> tag's onload event. Your source code example will still hold it's original spacings and
formats.

<HTML>
<script language=JavaScript>

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;
}

</script>

<BODY>
<form name=frmSubmit method=post >
<table border=0 cellspacing=1 cellpadding=1 width='70%' align=center>
<tr><td align=left><textarea name=txtTest cols=50 rows=1 style='overflow:hidden'> </textarea></td></tr>
<tr><td align=left><a href=# onclick="ResizeTextArea(document.frmSubmit.txtTest);" >Resize</a></td></tr>
</table></form></BODY></HTML>

Submission Date:  9/23/2005 2:48:57 PM
Submitted By:  Robbe Morris
My Home Page:  http://www.robbemorris.com

My Biography
Robbe has been a Microsoft MVP for C# since 2004. He is also the co-founder of EggHeadCafe. Robbe has extensive experience with web technologies, .NET, C#, CTI based applications, system administration, .NET Compact Framework, and data modeling. In his spare time, he blogs from time to time at http://robbemorris.blogspot.com