Count words in a textarea
Learn about .each() by EasyProgramming.net
by Nazmus Nasir
HTML
<!-- Easy jQuery - Counting words in textarea - #12 -->
<p>
Welcome to the 12th Easy jQuery Tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. In the Easy JavaScript series, we learned about how to count characters in a text area, I want to show you this example in jQuery but instead of characters, we'll count words.
</p>
<p>
You can find the Easy JS tutorial on <a href="https://www.easyprogramming.net/javascript/js_count_characters.php">Easy Programming</a>.
</p>
<p>
We'll be using the keyup jQuery event for this example:
</p>
<pre>
$('textarea').on('keyup', function(){
var count = $(textarea).val().trim().split(' ');
})
</pre>
<p>
The example is pretty straight forward so let's practice below.
</p>
<h2>
Let's practice:
</h2>
<p>
<textarea id="myText" height="500"></textarea>
</p>
<p>
<span id="wordCount">0</span> Words
</p>
CSS
textarea {
width: 500px;
height: 150px;
}
JavaScript
$('#myText').on('keyup',function(){
var count = $('#myText').val().trim().split(' ');
$('#wordCount').text(count.length);
});