Count characters in textarea Ask Question

Count characters in textarea Ask Question

I want to count characters in a textarea, so I just made:

<textarea id="field" onkeyup="countChar(this)"></textarea>

function countChar(val){
     var len = val.value.length;
     if (len >= 500) {
              val.value = val.value.substring(0, 500);
     } else {
              $('#charNum').text(500 - len);
     }
};

What's wrong with my piece of code? It does not work! Well, that was a newbie handwriting, need a help.

ベストアンサー1

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>

おすすめ記事