0

Here's a character counter code that I have. It's showing how many characters remaining.

HTML:
<textarea></textarea> <span id='remainingC'></span>

JS:
$('textarea').keypress(function(){

if(this.value.length > 300){
    return false;
}
$("#remainingC").html((300 - this.value.length)+ "/ 300");
});

But I have one problem. When I backspace, the number showing doesn't reflect and only when I start writing then the counter updates.

Any help would be appreciated!

rory-h
  • 660
  • 1
  • 12
  • 30

3 Answers3

2

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>
gyre
  • 16,369
  • 3
  • 37
  • 47
0

Use keydown event instead of keypress.

0

Use keyup instead of keypress. This gets all the key codes when the user presses something

jQuery: keyPress Backspace won't fire?

Community
  • 1
  • 1
jhhayashi
  • 361
  • 4
  • 14