Count words as user type – Textarea & Javascript

Demo

In this tutorial, we are going to teach you how you can count the number of words in textarea as user type in it. The first thing you need to do is to attach an onkeyup listener to your textarea tag. This function will be called whenever user pressed the key. Specifically, when the user’s finger is moving upwards after pressing the key, then this event is called. In this function, we are passing a parameter this means current node, which is textarea tag.

<textarea onkeyup="countWords(this);"></textarea>
<span id="words-counter"></span>

Then we created a span tag, you can create a div or paragraph as well. Give that span tag a unique ID so it can be accessible in Javascript. We will be displaying the number of words in this span tag.

Then we create this function in Javascript, first, we are getting the current text inside textarea field using the value attribute. Then we are applying a regular expression which states that:

Count the number of words
separated by spaces.

This will return an array, we simply have to calculate the length of that array. We are using a ternary operator to get value as 0 if the spaces array is null. Finally, we are displaying that length in the span tag using plain Javascript.

function countWords(self) {
	var spaces = self.value.match(/\S+/g);
	var words = spaces ? spaces.length : 0;

	document.getElementById("words-counter").innerHTML = words + " words";
}

That’s how you can count the number of words as user type in an input field using plain HTML and Javascript.Specifically in a <textarea> tag.

2 Replies to “Count words as user type – Textarea & Javascript”

  1. Hi Adnan, I like your teaching , please how can I make a count with Ajax and all in one file

Comments are closed.