Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

How To Using Multiple textarea autoexpand with jquery in one page

How to use textarea autoexpand with jquery inside a same page.

I'm trying to use some textarea like this on a same page:

<form action="#" method="#">
    <textarea name="text" id="textid"></textarea>
</form>

<form action="#" method="#">
    <textarea name="text" id="textid1"></textarea>
</form>

<form action="#" method="#">
    <textarea name="text" id="textid2"></textarea>
</form>

Then my textarea, I use jquery to be in autoexpand, but the autoexpand can only work in the first textarea and can not be used in the textarea below it.

Jquery script like this:

$(document).ready(function () {
        var textarea = document.querySelector('textarea');

        textarea.addEventListener('keydown', autosize);

        function autosize(){
            var el = this;
            setTimeout(function(){
                el.style.cssText = 'height:auto; padding:5px 0; margin-bottom: 10px;';
                // for box-sizing other than "content-box" use:
                // el.style.cssText = '-moz-box-sizing:content-box';
                el.style.cssText = 'height:' + el.scrollHeight + 'px';
            },0);
        }
    });

What should I do to make autoexpand work in all my textareas on this page?

Because I have tried to find it, but I have not found the same problem as this.

Thanks in advance.

Upvotes: 0

Views: 501

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51816

I converted your answer to use entirely jQuery, and fixed a few other issues you had:

$(function () {
  var $textareas = $('textarea');

  $textareas.on('input', autosize);

  function autosize() {
    var $this = $(this);

    $this
      .css({height: 'auto'})
      .css({height: $this.prop('scrollHeight')});
  }
});
textarea {
  box-sizing: content-box;
  resize: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="#">
  <textarea name="text" id="textid"></textarea>
</form>

<form action="#" method="#">
  <textarea name="text" id="textid1"></textarea>
</form>

<form action="#" method="#">
  <textarea name="text" id="textid2"></textarea>
</form>

Upvotes: 2

Related Questions