How to Create a Word Count with jQuery?

Estimated read time 2 min read

To create a word count with jQuery, you can use the split() method to separate the input text into an array of words, and then count the length of the array. Here’s an example:

HTML code:

<label for="input-text">Input Text:</label>
<textarea id="input-text"></textarea>
<span id="word-count">0</span> words

In this example, we have an HTML label element and a textarea element with the ID “input-text”. We also have a span element with the ID “word-count” that will be used to display the word count.

jQuery code:

$(document).ready(function(){
	$("#input-text").keyup(function(){
		var inputText = $(this).val();
		var wordCount = inputText.split(" ").length;
		$("#word-count").text(wordCount);
	});
});

In this example, we use the $() function to select the textarea element with the ID “input-text”. We use the keyup() method to listen for key presses in the input field. When the user types or deletes text, we get the input value using the val() method of the $(this) object.

We use the split() method to separate the input value into an array of words, using a space character as the separator. We then get the length of the array using the length property, which gives us the word count.

Finally, we update the text of the $("#word-count") element with the word count using the text() method.

This code updates the word count in real-time as the user types, and is a simple way to provide feedback on the length of their input text.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply