William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

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.
$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 response to “PHP: auto adjust textarea height

  1. powercashadvance.com 10/26/2011 at 5:05 pm

    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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: