I have a form that with a textarea and I'm trying to prevent users from pasting more than 1000 characters into it. I have a div that displays the number of characters left as the user types, which is the problem. I have the pasting part working, but I'm also trying to set the character counter at the same time.
Here's the code:
<textarea name="Note" id="Note" cols="80" rows="5" class="text-input shadow form-control" maxlength="1000"></textarea>
<div id="NoteLength"></div>
<div>characters remaining.</div>
and the jQuery:
$("#NoteLength").text("1000");
//user is typing
$("#Note").keyup(function () {
el = $(this);
if (el.val().length >= 1000) {
el.val(el.val().substr(0, 1000));
} else {
$("#NoteLength").text(1000 - el.val().length);
}
});
//user is pasting
$("#Note").blur(function (event) {
var maxLength = 1000;
var length = this.value.length;
if (length > maxLength) {
$("#NoteLength").text("0");
this.value = this.value.substring(0, maxLength);
}
});
It's truncating the text as expected, but it's not resetting the NoteLength div to if I paste a large chunk of text, say 1500 characters. If I paste blocks of 200 characters, the counter works fine. Works if I backspace over the last character pasted in too, just not when I go way over in one paste which is unfortunately the most likely user scenario.