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

Implement the function of counting the number of words in Textarea in JavaScript and prompting for characters that can still be entered

怪我咯
Release: 2017-07-04 15:07:30
Original
1314 people have browsed it

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. In fact, js can also be implemented. Let’s explain it to you with an example.

Now popular Twitter and other micro-blogging websites have a good user experience, that is, 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. The limit is 140 characters. In your microblog, such small tips can greatly enhance the user experience.

If this technology is implemented, I conducted some research and found that the implementation is actually quite simple. A few lines of code can complete the Input character statistical function. After actual testing, its effect on text The statistics are exactly the same as those of Twitter and other microblogs.

The method of use is to first add a span to display the remaining number of words, and then add an onkeydown and onkeyup event to the Textarea to call another paragraph JavaScript function, the parameters called by the function are the id of span and the id of textarea, and then use innerHTML in JavaScript to return the calculated remaining word count.

Core Javascript code:

The code is as follows:

<span style="font-size:18px;"><script language="javascript"> 
function countChar(textareaName,spanName) 
{ 
document.getElementById(spanName).innerHTML = 140 - document.getElementById(textareaName).value.length; 
} 
</script> 
可以输入<span id="counter">140</span>字<br/> 
<textarea id="status" name="status" rows="6" cols="40" onkeydown=&#39;countChar("status","counter");&#39; 
onkeyup=&#39;countChar("status","counter");&#39;></textarea></span>
Copy after login

The above is the detailed content of Implement the function of counting the number of words in Textarea in JavaScript and prompting for characters that can still be entered. 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!