Home >Web Front-end >JS Tutorial >Implement the function of counting the number of words in Textarea in JavaScript and prompting for characters that can still be entered
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='countChar("status","counter");' onkeyup='countChar("status","counter");'></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!