Skip to content

Instantly share code, notes, and snippets.

@neilgee
Last active January 30, 2023 20:34
Show Gist options
  • Save neilgee/51cd27a3edd74b615149 to your computer and use it in GitHub Desktop.
Save neilgee/51cd27a3edd74b615149 to your computer and use it in GitHub Desktop.
Gravity Form Word Count
<?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.*/
/*Source http://www.gravityhelp.com/forums/topic/maximum-word-count#post-149331*/
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>');
});
});
@Akrasnovskis
Copy link

Is there any way when the field reached the number of words, it won't delete them, just stop? even after copy-paste higher number of words?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment