mcmwhfy
mcmwhfy

Reputation: 1686

Textarea increase ++ one row on enter and keypress using .attr() update

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.

Upvotes: 1

Views: 3697

Answers (2)

Veselov Pavel
Veselov Pavel

Reputation: 1

$('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.

Upvotes: 0

Josh Stevenson
Josh Stevenson

Reputation: 905

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);
    };
});

Upvotes: 3

Related Questions