4

I was wonder how I can create a text input that has an auto-adjustable height so that it gets taller to fit your text? For example, if I start typing a paragraph, it expands from a few lines to fit the paragraph.

Here's what I've currently got:

#commenttext {
  width: 413px;
  min-height: 22px;
  max-height: 100%;
  display: inline;
  font-size: 11px;
  color: #777777;
  word-wrap: break-word;
  font-family: "Open Sans", "Tahoma";
  top: 7px;
  position: relative;
  left: 7px;
  padding-left: 7px;
}
<form action="" method="POST">
  <input type="text" id="commenttext">
</form>

But that's just a normal text area.

How can I make that text area get taller as I type more lines? Do I need Javascript?

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47
ThinkkSo
  • 169
  • 2
  • 11

2 Answers2

10

Here's a CSS-only solution: Use a div with contenteditable set to true.

<div contenteditable="true"
    style="width:200px;min-height:20px;border:1px solid #ccc;"></div>

See this JSFiddle for an example.

EDIT: If you want to be able to submit this text, you'll need a little bit of javascript to put it into an input field. Add this to your form:

<form onsubmit="document.getElementById('hidden_data').value=document.getElementById('showing_data').innerHTML;">
    <input id="hidden_data" name="data" type="hidden"/>
    <div id="showing_data" contenteditable="true"
        style="width:200px;min-height:20px;border:1px solid #ccc;"></div>
</form>

This will put the contents of the div into a hidden input field so it will be submitted to the server through POST with anything else.

See this (updated) JSFiddle for an example.

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47
0

Take a look at this post here:

Creating a textarea with auto-resize

It has all the code needed (HTML and Javascript) to accomplish what you want.

Community
  • 1
  • 1
Charlie74
  • 2,883
  • 15
  • 23
  • Okay if i do use this way will i be able to fix the textarea input by myself? because if i can i'd rather not use that – ThinkkSo Oct 10 '13 at 03:20
  • What do you mean by "fix the text area"? When you are using textarea, it actually allows you to resize by dragging the box to the size you want. That happens without any code. If you want the textarea to increase automatically, you'll need some Javascript :) – Charlie74 Oct 10 '13 at 03:22
  • okay yeah like you said dragging the box size, i dont want to be able to do that i want it to be auto lol – ThinkkSo Oct 10 '13 at 03:24