How to get character count using JavaScript

Counting the number of characters in a textarea is a common requirement in website development. There can be various reasons for that like enforcing a character limit or providing a live character count for user input, JavaScript offers a simple and effective way to achieve this.

In this blog post, we will explore how to make a character count in a textarea using JavaScript, along with an example to demonstrate the implementation.

Let's dive into a practical example of implementing a character count feature for a textarea using JavaScript. Suppose we have an HTML form with a textarea element and a label to display the character count:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Character Count Example</title>
  <style>
    #character-count {
      color: gray;
      font-size: 12px;
    }
  </style>
</head>
<body>
  <form>
    <label for="message">Message:</label><br>
    <textarea id="message" rows="8" cols="50"></textarea><br>
    <span id="character-count">Characters: 0</span>
  </form>

  <script>
    const messageInput = document.getElementById('message');
    const characterCount = document.getElementById('character-count');

    messageInput.addEventListener('input', function() {
      const message = messageInput.value;
      const count = message.length;
      characterCount.textContent = 'Characters: ' + count;
    });
  </script>
</body>
</html>

In the above example, we have created a form with a textarea element that has an id of "message". We also have a label associated with the textarea and a span element with a specific ID to display the character count.

In JavaScript, we retrieve the user input and counted the number of characters in string using the getElementById() method. We also added an event listener for textarea so Whenever the user inputs or deletes something in the text area then it will run our logic. 

Inside the event listener, we retrieve the current value of the textarea and calculate its length. That calculated length will be displayed to the user.

Conclusion

Counting the number of characters in a textarea using JavaScript is a valuable feature to enhance user experience and enforce text length limits. However, we can limit the number of character inputs and also import this logic for validation.