JavaScript: live character count
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.
It is possible to show the countdown using a JavaScript function called on key up. Let's see how we can do it.
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.
It is possible to show the countdown using a JavaScript function called on key up. Let's see how we can do it.
The HTML
We 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.The function
The JavaScript function is simple and should be placed in the head of your page:
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.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.