JavaScript statistics Textarea word count and prompt can also enter the character

  • 2020-03-30 03:19:31
  • OfStack

Popular microblogging sites such as Twitter have a great user experience, which is that when you type text in a text box, it automatically counts the characters you type and displays the characters you can type. In a 140-character microblog, such tips can enhance the user experience.


What about this technology? I did some research and found that it was actually quite simple to implement. It took only a few lines of code to complete the input character statistics function.

To use this method, first add a span to display the remaining words, then in the Textarea, add an onkeydown and onkeyup events, call another JavaScript function, function call for the id of the span and the id of the Textarea, and then in JavaScript use innerHTML to return the calculated remaining words.

Core Javascript code:

 
<span style="font-size:18px;"><script language="javascript">
function countChar(textareaName,spanName)
{
document.getElementById(spanName).innerHTML = 140 - document.getElementById(textareaName).value.length;
}
</script>
You can enter <span id="counter">140</span> word <br/>
<textarea id="status" name="status" rows="6" cols="40" onkeydown='countChar("status","counter");'
onkeyup='countChar("status","counter");'></textarea></span>

PS: this site also provides an online tool about word count, interested friends can refer to:

Online word count tool:

(link: http://tools.jb51.net/code/zishutongji)


Related articles: