PHP: auto adjust textarea height

PHP: auto adjust textarea height

I wrote a simple PHP code to auto adjust textarea height:

function set_height($str) {
  $ary = explode("\n", $str);
  $style = '';
  if(is_array($ary) && count($ary)>1) {
    $height = 18 * count($ary);
    $style=' style="height:'.$height.'px; width:600px;" ';
  }
  return $style;
}

It is very stright:

  • How many line of the displayed content?
  • The linkes times 18 will be the textarea height (estimated)
  • add the dynamic data as a style attribue of the textarea.

That’s it. The following is the samples to use it:

// 1. set variables.
<php
$s1 = "this is first line.\nthis is second line.\nthis is third line.\nthis is fifth line.\nthis is sixth line.";
$s2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Cras semper, sem id semper tempus, 
risus risus commodo metus, 
vel auctor lacus augue non tellus. 
Sed hendrerit euismod turpis at porta. 
......
";
?>
// 2. testing.
<textarea <?=set_height($s1);?> ><?=$s1;?></textarea>
<br />
<textarea <?=set_height($s2);?> ><?=$s2;?></textarea>

They display different height according to content. Pretty cool.

One thought on “PHP: auto adjust textarea height

  1. We fully appreciate your blog post. You can find a lot of methods we could put it to proper use with the help of little or no effort with time and hard earned money. Thank you so much regarding helping make this post answer many issues we have had before now.

Leave a comment