Home  >  Article  >  Web Front-end  >  Javascript code to implement word count

Javascript code to implement word count

怪我咯
怪我咯Original
2017-07-04 15:05:552218browse

Nowadays, popular microblogging websites such as Twitter have a good user experience. When entering text in the text box, the entered characters will be automatically counted and the characters that the user can still enter will be displayed. After the limit of 140 In a microblog with a single word, such small tips can greatly enhance the user experience.

Word count function, the principle is to add onKeyupevent to textarea. The event reads the textarea content and obtains the length, and assigns it to the text node that counts the word count, here One thing to note is that adding onKeypress and onKeydown events can also achieve the effect, but they have some shortcomings and may cause misunderstandings in some cases. I have tried them both, but I feel that they only Using an onKeyup event is the wisest choice.

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

<body>
<p class="reply">
 <textarea id="test" onKeyUp="cal_words()"></textarea>
 <p>字数:<span id="num">0</span></p>
</p>
</body>
</html>

The above is the detailed content of Javascript code to implement word count. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn