javascript

Count the total number of characters in a textarea while typing in javascript

In this code example, we’re going to figure out how to count the total number of characters in a textarea while a user types. This is a simple example, with no libraries or helpers, just straight-up vanilla javascript.

const textarea = document.getElementById('textarea');
const show_counter = document.getElementById('show_counter');
const max_length = textarea.getAttribute('maxlength');

textarea.addEventListener('input', function (e) {
    const counts = this.value.length;
    show_counter.innerHTML = `${counts}/${max_length}`;
});

We have created a textarea and div tag in our HTML and using their ids we are getting them our javascript code. Full HTML code to show the counts of characters in a textarea is below.

<textarea id="textarea" maxlength="20" placeholder="Enter some text..."></textarea>
<div id="show_counter"></div>

<script>
const textarea = document.getElementById('textarea');
const show_counter = document.getElementById('show_counter');
const max_length = textarea.getAttribute('maxlength');

textarea.addEventListener('input', function (e) {
    const counts = this.value.length;
    show_counter.innerHTML = `${counts}/${max_length}`;
});
</script>

Live Demo

Was this helpful?