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);
}
});
});
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:
Javascript: