开发者

add new row to textarea input while editing

开发者 https://www.devze.com 2023-03-09 21:35 出处:网络
I wonder how to add new row/line to textarea while editing that is when the number of letters exceeds number of cols of the textarea add new 开发者_开发技巧line automatically.$(\'textarea\').keyup(fun

I wonder how to add new row/line to textarea while editing that is when the number of letters exceeds number of cols of the textarea add new 开发者_开发技巧line automatically.


$('textarea').keyup(function (e) {
    var rows = $(this).val().split("\n");
    $(this).prop('rows', rows.length);
});


Some basic code to achieve this, tested in this jsfiddle (http://jsfiddle.net/NZbZn/). It will need work, obviously, but shows the basic concept.

jQuery(document).ready(function(){

    //after typing occurs
    jQuery('textarea#expander').keyup(function(){

        //figure out how many chars
        var length = jQuery(this).val().length;

        //if more than 10
        if(length > 10){

            //if the modulus 10 of the length is zero, there are a multiple of 10 chars, so we need to extend by a row
            //(NOTE the obvious problem - this will expand while deleting chars too!)
            if((length % 10) == 0){

                //figure out the number of rows, increment by one, and reset rows attrib
                var rows = jQuery(this).attr('rows');
                rows++;

                jQuery(this).attr('rows', rows);    
            }  
        }   
    });    
});

Again though, consider the UI implications first.


You can use jQuery AutoResize Plugin: http://james.padolsey.com/javascript/jquery-plugin-autoresize/


You could do something like this:

<textarea id="ta" onkeyup="checkScroll(this)" style="height:4em; overflow:auto">
asdf
</textarea>

<script>
function checkScroll(obj) { 
  if(obj.clientHeight < obj.scrollHeight) {
    obj.style.height = (parseInt(obj.style.height)+1) + 'em';
  }
}
</script>

And you could add a height limit in the "if" condition if you wanted.

(Didn't worry about making this unobtrusive -- just getting the point across.)


try this

var txt = $("textarea#idhere");
txt.val( txt.val() + "\nSomething here\n\nAgain");


Here's plain JS one liner that automatically sets the number of rows of the textarea to the number of lines that it contains:

elt = document.getElementsByTagName('textarea')[0]

elt.addEventListener('keyup',()=>elt.setAttribute('rows',elt.value.split('\n').length))
<textarea rows='1'>Type some lines!</textarea>

0

精彩评论

暂无评论...
验证码 换一张
取 消