3
I am writing this code which is to count the amount of characters remaining in a textarea. At first it seemed very simple and has enough documentation on the internet. But I realized that when I copy and paste some text in the textarea, the total remaining characters are positive, that is, I can still type. However, that is not the case. In addition to not allowing typing more characters, even if I delete some of the characters with Backspace I can’t type anymore. For example, if the text ends in "ball" I can not write "ball" and if I delete for just "bol" (removing the "a") I can no longer write "ball".
To be clear, the code below works under normal conditions of temperature and pressure, but when a "Paste" occurs it gets the anomalous behavior, which is to present the amount of characters remaining, for example 200, and does not allow more data insertion. Follow the code I made:
$("#textAreaComplemento").bind("keyup change", function (e) {
calculaCaracteresRestantes();
});
function calculaCaracteresRestantes() {
if ($('#textAreaComplemento').val() == undefined) { return false; }
var text_length = $('#textAreaComplemento').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining);
return true;
}
any suggestion of what may be will be welcome.
EDIT: To play, just copy the code that is in this fiddle’s html comment http://jsfiddle.net/sLr8co1n/4/. Paste the code as much as you can into the textarea and then try typing.
Works well for me... You could join the event
paste
in that.bind()
. Take a look here and give an example of the wrong behavior that obtains: http://jsfiddle.net/n78n5vww/– Sergio
@Interesting, I put the maxlength in your code to look like mine. It’s working fine, but do the following: if I copy only one line of the Notepad with blank spaces and everything else and paste until it reaches the maximum amount, the behavior is ok. But I tried copying a text with lines, paragraphs and blanks and the behavior I described appears. Follow the updated fiddle. The mass I tested is in the html snippet commented on fiddle. http:/jsfiddle.net/sLr8co1n/4/
– Paulo Henrique Queiroz
I’m suspicious of damn special characters...
– Paulo Henrique Queiroz
does not work, @qmechanic73. The maxlength attribute is required in this case. To reproduce, just copy the code that is in the html comment of this fiddle http://jsfiddle.net/sLr8co1n/4/. Paste the code into the textarea as much as you can and then try to type.
– Paulo Henrique Queiroz
Why is maxlength necessary? If you control content size via script?
– Moykn