character counter – backspace doesn’t reflect on characters remaining

The problem is that .keypress() does not fire when the backspace is used. You should use the input event instead. Also, Math.max greatly simplifies your remaining character calculation.

If you want to enforce an actual cap on the number of characters in your <textarea>, you could always add the attribute maxlength="300".

$('textarea').on('input', function() {
  $('#remainingC').text(
    Math.max(0, 300 - this.value.length) + ' / 300'
  )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea maxlength="300"></textarea> <span id='remainingC'></span>

Leave a Comment