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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With