Count words as user type - Textarea & Javascript

Count words as user type – Textarea & Javascript

0
(0)

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.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





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

Leave a Reply

Please disable your adblocker or whitelist this site!