In many situation, we offer the user the possibility of filling in a form and specifically a textarea. In those cases, we might decide to limit the number of characters and thus show the user how many remaining letters are available, with some sort of live character count.
The HTMLWe build the text area inside a form. In our example the calling of the function is placed in the form itself, but it possible to use it directly inside the textarea (if you prefer):
The textarea has a max length of 40 characters, and so we start our character countdown from that value. The span tag with a specific id (characterCount) will initially show a starting value of 40, and then the function count() will change that value on the key up event.
<input type="text" id="message" size="40" maxlength="40">
Character count: <span id="characterCount">40</span>
It basically inspects the length of our textarea which has an id="message". Then it changes the value inside the span with a value equal to 40 (our max length) minus the length of the textarea.
var characterCount = document.getElementById("message").value.length;
document.getElementById("characterCount").innerHTML = 40-characterCount;
Every time a new letter is inserted in the textarea the span value decreases by one, starting from 40.
We can obviously change the max length according to our need.
And that's all for today.