Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input field that gets taller as you type

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?

like image 661
ThinkkSo Avatar asked Dec 25 '22 19:12

ThinkkSo


1 Answers

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.

like image 172
Robbie Wxyz Avatar answered Dec 28 '22 09:12

Robbie Wxyz