Wednesday, March 11, 2009

Finally :: Auto Adjusting TextBox Height

It took a while to find what I was looking for, but I've finally found it! A way to Auto Adjust the Height of a Multiline TextBox or TextArea. The solution that I found involves a small bit of javascript, but does some pretty cool automagic auto adjusting. Give it a try HERE.

Here's the code, adjust to your Specs using textarea or ASP:TextBox Controls:

<body onload="cleanForm();">
<script type="text/javascript">
<!--
function countLines(strtocount, cols) {
var hard_lines = 1;
var last = 0;
while ( true ) {
last = strtocount.indexOf("\n", last+1);
hard_lines ++;
if ( last == -1 ) break;
}
var soft_lines = Math.round(strtocount.length / (cols-1));
var hard = eval("hard_lines " + unescape("%3e") + "soft_lines;");
if ( hard ) soft_lines = hard_lines;
return soft_lines;
}
function cleanForm() {
var the_form = document.forms[0];
for ( var x in the_form ) {
if ( ! the_form[x] ) continue;
if( typeof the_form[x].rows != "number" ) continue;
the_form[x].rows = countLines(the_form[x].value,the_form[x].cols) +1;
}
setTimeout("cleanForm();", 300);
}
// -->
</script>

<form action="index.php" method="get">
<p><textarea cols="60" rows="2" name="reason">Some text</textarea></p>
</form>

2 comments:

David J Barnes said...

This is a pretty sweet solution.

Donnie Franzen said...

it's bananas and works in IE and Firefox as well.