Home  >  Article  >  Web Front-end  >  Implement the function of counting the number of words in Textarea in JavaScript and prompting for characters that can still be entered

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

怪我咯
怪我咯Original
2017-07-04 15:07:301369browse

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>

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!

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