1

I have a textarea on which I want to increase his height with one row on every enter and on each time when text it goes into another row wile typing. So I have 3 conditions, when is displayed I want to number all used rows and set rows height based on this:

one: var countRows = $("textarea").val().split(/\r|\r\n|\n/).length;

two: when keypress == 13 is used

and three: when text it goes into another row wile typing

Till now I have achived this but is not really working :|

var countRows = $("textarea").val().split(/\r|\r\n|\n/).length;   
var keynum = 13; //enter keynum

//for default state
//not calculating 
$("textarea").attr("rows", countRows + 1);

//for enter key 
//not really working
$("textarea").on('keypress', keynum, function() {
   $(this).attr("rows", countRows + 1);
     // alert("jjj");
});

//for case whentext it goes into another row wile typing

I just want to do that using .attr() and updating that attribute "rows" when one more row is added or removed.

mcmwhfy
  • 1,654
  • 5
  • 36
  • 58
  • for your key press, that format looks wrong. that's the format for a delegate. try $("textarea").on('keypress', function(e){ if (e.keyCode == 13) { ... }}); – Taplar Apr 29 '15 at 12:53
  • 2
    possible duplicate of [Auto expand a textarea using jQuery](http://stackoverflow.com/questions/2948230/auto-expand-a-textarea-using-jquery) – Josh Stevenson Apr 29 '15 at 12:54
  • @Taplar .on( "keypress", handler ) seems to be ok on jQuery events – mcmwhfy Apr 29 '15 at 13:10
  • 1
    @mcmwhfy right but in his example he has .on("keypress", keynum, function() {}) so if he's trying to get the keynumber pressed passed in like that, instead of that being a selector, then that will not work. on, sorry, lol, missed that you were the original poster. – Taplar Apr 29 '15 at 13:11
  • @JoshStevenson Is not duplicated I just want to do that using .attr() and updating that attribute "rows" when one more row is added or removed. – mcmwhfy Apr 29 '15 at 13:44

2 Answers2

2

From https://stackoverflow.com/a/10080841/4801673

$("textarea").keyup(function(e) {
    while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
        $(this).height($(this).height()+1);
    };
});
Community
  • 1
  • 1
Josh Stevenson
  • 895
  • 5
  • 17
0
$('textarea').keyup(function(e) {
    var $lineHeight = $(this).height() / $(this).get(0).rows;
    var $lines = $(this).val().split(/\r|\r\n|\n/).length;
    $(this).get(0).rows = $lines;
});

Increase size if add new lines to textarea. Decrease size if remove lines from textarea. Nothing to do if lines not added/removed in textarea.