简体   繁体   中英

Dynamic height for text area

Is there a way for me to increase the height of the textarea

<textarea class="form-control"></textarea>

instead of the scroll feature that we get when the input exceeds the width and height of the field? For example if the user enters 2 paragraphs the entire paragraph should be visible. The textarea should only have 1 or 2 line heights at the beginning when it is empty.

You can use below script to achieve that.

$("#textarea").on("keyup", function(event){
    if($(event.currentTarget).outerHeight() < $(event.currentTarget)[0].scrollHeight){
    $(event.currentTarget).height($(event.currentTarget)[0].scrollHeight);
  }
});

I have created snippet as well.

 $("#textarea").on("keyup", function(event){ if($(event.currentTarget).outerHeight() < $(event.currentTarget)[0].scrollHeight){ $(event.currentTarget).height($(event.currentTarget)[0].scrollHeight); } }) 
 #textarea{ height:20px; overflow:hidden; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea class="form-control" id="textarea"></textarea> 

You can also test it here.. https://jsfiddle.net/zrnp7gkm/8/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM