0

i want to have a text input with autoresize when the user types more then one line.

i tried using html5 contenteditable but it's too complicate to get the data. (this solution isn't working for me Extracting text from a contentEditable div and also there is this warning " It is also possible that an update to any browser could break this function if they change how they implement contentEditable.")

i also tried this plugin but i don't know how to update the textarea content. after typing if i'm checking for $('textarea').html() i'm getting empty value.

Edit: basically, the most important thing for me is to get line break if the user press on enter key.

Community
  • 1
  • 1
user2587454
  • 903
  • 1
  • 19
  • 44

3 Answers3

1

You can write your own plugin to autoresize a text area. Try this snippet:

$(document).ready(function() {
 $('.txt').on('keyup', function(event) {
     var textareaElm = event.target;
        if (textareaElm.scrollHeight > textareaElm.clientHeight) {
            textareaElm.style.height = textareaElm.scrollHeight + "px";
        }
 });
})
.txt {
 width: 200px;
 height: 50px;
 transition: height 0.2s linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea class="txt"></textarea>

Here is a jsfiddle for the same: http://jsfiddle.net/t1cg7f20/

This example uses jQuery. Let me know if you need a JS only solution.

Praveen Singh
  • 2,499
  • 3
  • 19
  • 29
0

To access a <textarea>s value you'll want to use

$('textarea').val()

It should also work with your plugin.

0

Thanks to @Praveen Singh, i'm using his code to autoresize:

$(document).ready(function() {
$('.txt').on('keyup', function(event) {
    var textareaElm = event.target;
    if (textareaElm.scrollHeight > textareaElm.clientHeight) {
        textareaElm.style.height = textareaElm.scrollHeight + "px";
    }
});

})

.txt {
width: 200px;
height: 50px;
transition: height 0.2s linear;

}

and replace(/\n\r?/g, '<br />') to show line break.

user2587454
  • 903
  • 1
  • 19
  • 44