I am working with PHP and I have a Textarea where a count is made for each character entered, it has a limit of 500 and it shows an alert when the limit is exceeded. It works very well but it has a problem, when copying and pasting or cutting direct information in the textarea, it stops counting and keeps the last value that was counted. That is why I request your help or guidance to solve this problem, my code is as follows:
<script>
$('#mensaje_ayuda').text('500 carácteres restantes');
$('#observaciones').keydown(function () {
var max = 500;
var len = $(this).val().length;
if (len >= max) {
$('#mensaje_ayuda').text('Has llegado al límite');
$('#mensaje_ayuda').addClass('text-danger');
$('#observaciones').addClass('is-invalid');
$('#inputsubmit').addClass('disabled');
document.getElementById('inputsubmit').disabled = true;
}
else {
var ch = max - len;
$('#mensaje_ayuda').text(ch + ' carácteres restantes');
$('#mensaje_ayuda').removeClass('text-danger');
$('#observaciones').removeClass('is-invalid');
$('#inputsubmit').removeClass('disabled');
document.getElementById('inputsubmit').disabled = false;
}
});
</script>
<textarea class="form-control" id="observaciones" name="observaciones"
placeholder="Observaciones..." rows="6" maxlength="500"></textarea>
<span class="help-block">
<p id="mensaje_ayuda" class="help-block">Cuerpo del mensaje de alerta</p>
</span>
As I told you in comments, you just have to change the event
keydown
toinput
and if it doesn't work, check the console for errors.Try this code snippet, I commented out the lines where you enable or disable the element
inputsubmit
because it doesn't exist in the HTML and it gave an error.Well, the thing is, you have to give it a new listener to listen to the event you hit, which is different from the keydown event (because it's a key combination).