Matthew Woodard
Matthew Woodard

Reputation: 754

How to do a Word Count on Multiple Textareas using jQuery?

I have successfully did a word count on a text area using the following JS:

   jQuery('span.after-amount').append(' - You have <span class="wordcount">0</span> words.'); 

   jQuery('textarea').on('input', function($) {

      var regex = /\s+/gi;
      var count =  jQuery(this).val().trim().replace(regex, ' ').split(" ").length;

      $('.wordcount').html(count);


    });

My HTML:

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea>
<span class="after-amount">You have <span class="wordcount">0</span> words.</span>

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea>
<span class="after-amount">You have <span class="wordcount">0</span> words.</span>

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea>
<span class="after-amount">You have <span class="wordcount">0</span> words.</span>

Here is a Fiddle.

I need to get a word count for each text area, is there an easy way to do this without selecting each textarea individually?

Upvotes: 0

Views: 1576

Answers (2)

DrKey
DrKey

Reputation: 3495

Just finding .wordcount into <li>

jQuery('textarea').on('input', function($) {
        var regex = /\s+/gi;
        var count =  jQuery(this).val().trim().replace(regex, ' ').split(" ").length;
        jQuery(this).parent().find('.wordcount').html(count);
);

Upvotes: 1

Aldi Unanto
Aldi Unanto

Reputation: 3682

This is my solution, first I change your event handler to keyup, and starting count of each textarea value's length using $(this) so you get the current textarea.

$(function(){
   $('textarea').on('keyup', function(){
      var wordsLength = $(this).val().length;
      $(this).next().find('.wordcount').html(wordsLength);
   });
});

Check this updated jsfiddle. Hope this helps

Upvotes: 1

Related Questions