Count characters in textarea

What errors are you seeing in the browser? I can understand why your code doesn’t work if what you posted was incomplete, but without knowing that I can’t know for sure.

You should probably clear the charNum div, or write something, if they are over the limit.

function countChar(val) {
  var len = val.value.length;
  if (len >= 500) {
    val.value = val.value.substring(0, 500);
  } else {
    $('#charNum').text(500 - len);
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea id="field" onkeyup="countChar(this)"></textarea>
<div id="charNum"></div>

Leave a Comment