← Back toHTML DOM

Count the number of characters of a textarea

Written byPhuoc Nguyen
Created
18 Mar, 2020
Category
Level 1 — Basic
Assume that we have a `textarea` and a normal `div` elements for showing how many characters user has been entering:
html
<textarea id="message"></textarea>
<div id="counter"></div>

Use the `maxlength` attribute

The `maxlength` attribute sets the maximum number of characters that user can put in the textarea.
html
<textarea maxlength="200" id="message"></textarea>

Count the number of characters

Handle the `input` event which is triggered if the value of element is changed:
js
const messageEle = document.getElementById('message');
const counterEle = document.getElementById('counter');

messageEle.addEventListener('input', function (e) {
const target = e.target;

// Get the `maxlength` attribute
const maxLength = target.getAttribute('maxlength');

// Count the current number of characters
const currentLength = target.value.length;

counterEle.innerHTML = `${currentLength}/${maxLength}`;
});
Good to know
The common mistake is to capture the `keyup` event. It doesn't work in some cases such as:
  • User drags a text into the textarea
  • User right-clicks in the textarea and chooses Paste from the context menu

Demo

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn