Home > Web Front-end > JS Tutorial > body text

JS implements word count function

怪我咯
Release: 2017-07-16 10:42:33
Original
3777 people have browsed it

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!