jessica February 2016

value.length not working as expected when backspacing

I'm trying to get the characters of a textarea using javascript, and it works fine when you're typing text inside the textarea, but when you're using backspacing, it gives the wrong length of characters.

<textarea id = 'textarea' onkeydown = "adjust()"></textarea>

<script>

function adjust() {

var length = document.getElementById("textarea").value.length+1;
alert("length: "+length);

} //end of function adjust()
</script>

For example:

Say, you start when 25 characters in the textarea. Then when you use backspace once:

It alerts: 26 characters; Use backspace again, and it will alert: 25 characters; Then, 24, 23, 22, 21.

Which isn't true, since it should be showing 24,23,22,21,20, and 19 instead. Why is it doing that, and how would we fix it?

Answers


Alien Bishop February 2016

Could it be due to the fact that you're listening to the onkeydown event, and the removal of each character doesn't register until after the backspace key is up again?


jessica February 2016

This works:

function adjust() {

var key = event.keyCode;
if (key == 8 || key == 46) {
var length = document.getElementById("textarea").value.length-1;
} //end of if (key == 8 || key == 46)
else {
var length = document.getElementById("textarea").value.length+1;
}
alert("length: "+length);

} //end of function adjust()

Post Status

Asked in February 2016
Viewed 2,564 times
Voted 10
Answered 2 times

Search




Leave an answer