JQuery loop on multiple items of the same CSS class

317 views Asked by At

I have multiple fields of the same class. The word count shows up correctly, but changes the value of every word count when one field has received input. Additionally, I'd expect the field to show a word count of 100 if no input exists, but it shows 0. Suggestions on improving the code below?

jQuery(document).ready(function() {
//Text area 100 word limit
jQuery('.100_wordCount').text("Word Count: 100");
    jQuery(".100_word_limit").on('keyup', function() {
        var words = this.value.match(/\S+/g).length;
        if (words > 100) {
            // Split the string on first 100 words and rejoin on spaces
            var trimmed = jQuery(this).val().split(/\s+/, 100).join(" ");
            // Add a space at the end to keep new typing making new words
            jQuery(this).val(trimmed + " ");
        }else if(words < 0){ 
            jQuery('.100_wordCount').text("Word Count: 100");
        }else{
            var wordsLeft = 100-words;
            jQuery('.100_wordCount').text("Word Count: " + wordsLeft);
        }
    });
});
1

There are 1 answers

2
Jason On BEST ANSWER

I'd wrap each textarea + word count (eg. in a div), and in the keyup event find the other child tag based on the shared parent element.

This example just grabs the immediate parent but you could do it based on a common ancestor or its class name.

eg. http://jsfiddle.net/mzqo2ruk/

Html:

<div>
    <textarea class="100_word_limit"></textarea>
    <p class="100_wordCount"></p>
</div>

Javascript:

jQuery(document).ready(function() {
//Text area 100 word limit
jQuery('.100_wordCount').text("Word Count: 100");
jQuery(".100_word_limit").on('keyup', function() {
        var words = this.value.match(/\S+/g).length;
        if (words > 100) {
            // Split the string on first 100 words and rejoin on spaces
            var trimmed = jQuery(this).val().split(/\s+/, 100).join(" ");
            // Add a space at the end to keep new typing making new words
            jQuery(this).val(trimmed + " ");
        }else if(words < 0){ 
            jQuery(this).parent().find('.100_wordCount').text("Word Count: 100");
        }else{
            var wordsLeft = 100-words;
            jQuery(this).parent().find('.100_wordCount').text("Word Count: " + wordsLeft);
        }
    });
});