Javascript realizes word count

  • 2020-07-21 06:44:56
  • OfStack

Word count function, the principle is to add onKeyup textarea events, events read textarea content and length, and the assigned to statistics of the text node, there is one point to note is to add onKeypress and onKeydown events also can achieve effect, but are insufficient, may cause misunderstanding in some cases, I tried to feel only 1 onKeyup event is the most sensible choice.


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> The test file </title>
<script>
function cal_words(){
  var length = document.getElementById("test").value.length;
  document.getElementById("num").innerHTML = length;
}
</script>
</head>

<body>
<div class="reply">
 <textarea id="test" onKeyUp="cal_words()"></textarea>
 <div> Word count: <span id="num">0</span></div>
</div>
</body>
</html>

This is the end of this article, I hope you enjoy it.


Related articles: