Home >Web Front-end >JS Tutorial >Code for calculating remaining word count using JS_javascript skills
Let’s take a look at the HTML code first:
Maximum text length: 250. Remaining: 250.
It can be seen that onkeyup is an event triggered when the user leaves the keyboard. The passed parameter is this (that is, the current document area)
Then take a look at the JS code:
The function first assigns a value to the maxChars variable (the maximum number of characters available in the input area. Note that this variable is a numerical value that can be used for calculation)
Then the value entered in the textarea is obtained from the parameters. Character length and compared with the previously specified maximum length.
When the input character length exceeds the range, use substring to forcefully limit its length (0, maxChars), which means that the input range is 0 characters to maxChars (variable) characters.
var curr = maxChars - which.value.length; is used to calculate how many characters are available and save the value in curr.
Finally, use getElementById to locate the object with id chLeft (span in this HTML), and use the toString method to change the value in curr into a string and feed it back to the span tag. <script> <BR>function checkLength(which) { <BR>var maxChars = 250; <BR>if (which.value.length > maxChars) <BR>which.value = which.value.substring(0,maxChars); <BR>var curr = maxChars - which.value.length; <BR>document.getElementById("chLeft").innerHTML = curr.toString(); <BR>} <BR></script>