Autoresize textarea remove lines in backspace
I have the following code to autoresist a textbox:
HTML:
<textarea class="autoresize" id="txt" rows="2"></textarea>
JS:
$('#txt').keydown(function(e) {
var $this = $(this),
rows = parseInt($this.attr('rows'));
// on enter, add a row
if (e.which === 13)
$this.attr('rows', rows + 1);
// on backspace, remove a row -- THIS IS THE PROBLEM
if (e.which === 8 && rows !== 2)
$this.attr('rows', rows - 1);
});
This works well, but when I press backspace to erase a letter from a word, it also deletes lines and that's my problem.
I want it to shrink when the user "deletes" blank lines, but I don't know how to achieve it.
If you want, you can check it out in this script .
+3
Gofilord
source
to share
2 answers
You need to check if the last line is empty. Demo .
if (e.which === 8 && rows !== 2) {
lines = $(this).val().split('\n');
if(!lines[lines.length - 1]) {
$this.attr('rows', rows - 1);
}
}
+2
Yury tarabanko
source
to share
Just count the length of the text you entered (in each one keydown
) and then when you use backspace check that the last character (get it using the index from the length) is \ n and then remove the line.
0
pavon147
source
to share