Home  >  Article  >  Web Front-end  >  JS implements word count function

JS implements word count function

怪我咯
怪我咯Original
2017-07-16 10:42:333798browse

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.

This article The article mainly introduces the function of using JS to implement word count. The example code is as follows

<!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 JS implements word count function. 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