Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding a textarea depending on how much text it has in it (jquery)

How can I get a textarea to initially have only 1 row, but then when the text reaches the end of the row to add another row, and keep doing this up until a maximum of 5 rows?

like image 591
user852974 Avatar asked Nov 29 '11 20:11

user852974


1 Answers

Something like this:

<textarea id="foo" rows="1" cols="40"></textarea>

$(function () {

    $("#foo").on("keyup", function () {

       if ($(this).attr('rows') < 5 &&
           parseInt($(this).val().length/$(this).attr('cols')) >= $(this).attr('rows'))
           $(this).attr("rows", parseInt($(this).attr("rows"))+1);

    });

});

http://jsfiddle.net/Q3pPT/

edit Slight improvements to handle newlines:

$(function () {

    $("#foo").on("keyup", function (e) {

       if ($(this).attr('rows') < 5)
       {
           if (
               parseInt($(this).val().length/$(this).attr('cols'))+
               ($(this).val().split("\n").length-1) 

               >= 

               $(this).attr('rows')
              )
               $(this).attr("rows", parseInt($(this).attr("rows"))+1);

           if (e.keyCode == 13)
           {
               $(this).attr("rows", parseInt($(this).attr("rows"))+1);
           }
       } 

    });

});

http://jsfiddle.net/Q3pPT/2/

like image 128
Jake Feasel Avatar answered Oct 11 '22 21:10

Jake Feasel