Another way to do it... we started with the resource in http://roshanbh.com.np/2008/10/jquery-plugin-word-counter-textarea.html but wound up a little differently.
Save this in /themes/yourtheme/js/ as jquery.gravity_wordcount.js:
jQuery(document).ready(function($) {
$("[class*='count[']").each(function() {
var elClass = $(this).attr('class');
var maxWords = 0;
var countControl = elClass.substring((elClass.indexOf('['))+1, elClass.lastIndexOf(']')).split(',');
if (countControl.length > 1) {
minWords = countControl[0];
maxWords = countControl[1];
} else {
maxWords = countControl[0];
}
$(this).find('textarea').bind('keyup click blur focus change paste', function() {
var numWords = jQuery.trim($(this).val()).replace(/\s+/g," ").split(' ').length;
if ($(this).val() === '') {
numWords = 0;
}
$(this).siblings('.word-count-wrapper').children('.word-count').text(numWords);
if (numWords > maxWords && maxWords != 0) {
$(this).siblings('.word-count-wrapper').addClass('error');
var trimmedString = '';
var wordArray = $(this).val().split(/[\s\.\?]+/);
for (var i = 0; i < maxWords; i++) {
trimmedString += wordArray[i] + ' ';
}
$(this).val(trimmedString);
}
else if (numWords == maxWords && maxWords != 0) {
$(this).siblings('.word-count-wrapper').addClass('error');
}
else {
$(this).siblings('.word-count-wrapper').removeClass('error');
}
}).after('<span class="word-count-wrapper">Total Word Count: <span class="word-count">0</span></span>');
});
});
In functions.php:
/* Gravity Forms Word Count Script */
function els_load_scripts() {
wp_enqueue_script('gravity-forms-word-count', get_stylesheet_directory_uri() . '/js/jquery.gravity_word_count.js', array('jquery'), '0.1', true);
}
add_action('wp_enqueue_scripts', 'els_load_scripts');
Then in the form, for fields that need the word count, add the class ‘els-word-count[300].' Change [300] as needed for the maximum words that can be added to that particular field.
Posted 11 years ago on Monday February 18, 2013 |
Permalink