Alpha5 Alpha5 - 7 months ago 19
HTML Question

Auto increase size of input with text entered

I have a HTML code in which the users enter the comment for a particular question if the size of comments are big i want my text box to auto increase in height with the comments
Below is my HTML code:

<label class="label-reports">Comments</label>
<input @((ViewBag.UserId != null && ViewBag.UserId == question.AnsweredBy) || (question.AnsweredBy == null) ? "" : "disabled") type="text" class="form-control" style="align-content:stretch; min-width:1200Px; width: auto !important" for="comments" value="@question.Comments" />


I tried to implement this

<textarea class="form-control" rows="5"></textarea>*


but did not succeed can someone suggest to increase the size of text box with increase in text

Answer

For <textarea> Elements...

If you aren't opposed to using a plug-in, you could use something like autosize, which will allow your <textarea> element to grow as expected :

<!-- Example autosize.js CDN Reference -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/autosize.js/3.0.15/autosize.min.js'></script>
<script>
    // Automatically size all of your <textarea> elements as you type
    autosize(document.querySelectorAll('textarea'));
</script>

enter image description here

Interactive Example

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Autosize Example</title>
</head>
<body>
  <pre>Start typing (and press Enter a few times)</pre>
  <textarea></textarea>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/autosize.js/3.0.15/autosize.min.js'></script>
  <script>
    autosize(document.querySelectorAll('textarea'));
  </script>
</body>
</html>

For <input> elements...

<input> elements don't have to be left out. There is an aptly-named autosize-input plug-in that essentially accomplishes the same basic thing :

<!-- Example autosize.js CDN Reference -->
<script src="https://rawgit.com/yuanqing/autosize-input/master/autosize-input.min.js"></script>
<script>
    // Automatically size all of your <textarea> elements as you type
    autosizeInput(document.querySelector('#YourInputID'));
</script>